알고리즘/LeetCode
[LeetCode/easy/Array] Single Number
녕이
2022. 8. 16. 18:27
728x90
https://leetcode.com/problems/single-number/
Single Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
int singleNumber(vector<int>& nums) {
for(int i=0; i<nums.size(); i++){
if(count(nums.begin(), nums.end(), nums[i]) == 1) return nums[i];
}
return 0;
}
간과한 것이 하나 있는데 짝이 있는 것과 오직 하나만 있는 애 하나 이렇게 구성되어 있는 배열이므로
sort 하는 것도 좋은 선택이다. 정렬하고 앞에서부터 보면 빠르게 찾을 수 있다.
이렇게 하면 위 코드보다 더 빠르게 끝낼 수 있다.
int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
for(int i=1; i<nums.size(); i+=2){
if(nums[i-1] != nums[i]) return nums[i-1];
}
return nums[nums.size()-1];
}
728x90