반응형
LV. Easy 😎
https://leetcode.com/problems/single-number/
문제
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
- 1 <= nums.length <= 3 * 104
- -3 * 104 <= nums[i] <= 3 * 104
- Each element in the array appears twice except for one element which appears only once.
문제 해결법
값이 같은 숫자가 2개의 쌍을 가지고 있으니, 정렬을 해서 2개씩 확인해줘서 값이 다를 때 홀수 값을 리턴해주면 해결 완료!
해결 코드
class Solution {
public:
int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 1; i += 2) {
if (nums[i] != nums[i + 1])
return nums[i];
}
return *(nums.end() - 1);
}
};
728x90
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 39) Combination Sum (0) | 2022.02.17 |
---|---|
leetcode 24) Swap Nodes in Pairs (0) | 2022.02.16 |
leetcode 104) Maximum Depth of Binary Tree (0) | 2022.02.14 |
leetcode 78) Subsets (0) | 2022.02.13 |
leetcode 127) Word Ladder (0) | 2022.02.12 |
댓글