[Algorithm] Leetcode_Single Number

JAsmine_log·2024년 2월 19일

Problem

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.

Analysis & Solution

  • 같은 숫자가 있으면 Fasle, 없으면 True라고 생각
  • Bitwise 특성 이용하기
  • 모든 숫자를 XOR 비트 연산하면, "숫자가 같은 경우가 존재하면 0"으로 표기됨.
    이후, 남는 숫자만 반환!

Code

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for (auto i : nums) {
            ans ^= i;
        }
        return ans;
    }
};

Tip

Bitwise(비트연산자) : https://velog.io/@jasmine_s2/C-Bitwise-operator
C++ auto : https://velog.io/@jasmine_s2/C-auto

profile
Everyday Research & Development

0개의 댓글