Algorithm/Leetcode

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

junz 2023. 2. 21. 20:46
728x90
반응형

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

 

문   제 : 

정렬된 정수 배열 nums가 주어진다. 

nums 배열 안의 원소들은 한 숫자를 제외하고 모두 두 개씩 들어있다.

딱 하나만 들어있는 그 숫자를 구해라.

 

Constraint

{ 1 <= nums.length == 10^5 }

{ 0 == nums[i] <= 10^5 }

 

 

Example )

Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2

//////////////////////////////////////////////////////////

Input: nums = [3,3,7,7,10,11,11]
Output: 10

 



접   근 : 

배열을 두 개씩 묶어서 검사한다.


해   결 : 

배열을 두 개씩 보는데, 두 개가 같은 숫자면 pass이다.

만약 두 개가 같지 않다면, 처음 나온 숫자가 한 개만 있는 숫자이다.

 

만약 반복문을 끝까지 돌았는데도 함수종료가 되지 않았다면 맨 마지막 숫자가 하나만 있는 숫자라는 뜻이다.

 


 

결   과  :

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int n = nums.length;

        if(n == 1) return nums[0];
        
        for(int i=0; i<n-1; i=i+2){
            if(nums[i] != nums[i+1]) return nums[i];
        }

        return nums[n-1];

    }
}
728x90
반응형