Step-by-Step

[Java] Daily LeetCode Challenge 540. Single Element in a Sorted Array 본문

언어/JAVA

[Java] Daily LeetCode Challenge 540. Single Element in a Sorted Array

희주(KHJ) 2023. 2. 21. 17:45

https://leetcode.com/problems/single-element-in-a-sorted-array/description/

 

Single Element in a Sorted Array - LeetCode

Can you solve this real interview question? Single Element in a Sorted Array - You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element

leetcode.com

 

HashMap을 이용해서 개수를 기록한다.

Last 변수를 이용해서 현재 값과 이전 값이 다를때, HashMap에 있는 개수가 1개 밖에 되지 않으면 이전 값을 return 해준다.

 

[코드]

class Solution {
    public int singleNonDuplicate(int[] nums) {
        HashMap<Integer, Integer> hm = new HashMap<>();
        
        int last = nums[0];
        for(int i : nums){
            if(i!=last && last != -1){
                if(hm.get(last)!=2)
                    return last;
            }
            last = i;
            hm.put(i,hm.getOrDefault(i,0)+1);
        }
        return last;
    }
}
Comments