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
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy/String] Reverse Prefix of Word (0) | 2022.08.16 |
---|---|
[LeetCode/easy/TwoPointer] Find First Palindromic String in the Array (0) | 2022.08.16 |
[LeetCode/easy/Array] Best Time to Buy and Sell Stock (0) | 2022.08.16 |
[LeetCode/easy/Array] Pascal's triangle II (0) | 2022.08.16 |
[LeetCode/easy/Array] Pascal's triangle (0) | 2022.08.16 |