๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Single Number

by dkswnkk 2021. 11. 19.

๋ฌธ์ œ

 

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

 

์ฝ”๋“œ

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        map<int,int>m;
        int ans;
        
        for(int i:nums) m[i]++;
        for(auto it = m.begin(); it!=m.end(); it++){
            if(it->second==1){
                ans=it->first;
                break;
            } 
        }
        return ans;
    }
};

 

ํ’€์ด

๋‹จ์ˆœํžˆ ๋ฐฐ์—ด์—์„œ ์ค‘๋ณต๋˜์ง€ ์•Š์€ ๋‹จ ํ•˜๋‚˜์˜ ์ˆ˜๋ฅผ ์ฐพ์•„์„œ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค. ๋‚˜๋ฆ„ ์œ„ ํ’€์ด์ฒ˜๋Ÿผ ํ’€์—ˆ์„ ๋•Œ O(n)์ด๊ธฐ์— ํšจ์œจ์ ์ธ ์ฝ”๋“œ๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ  ์ œ์ถœํ–ˆ์œผ๋‚˜, ์‹œ๊ฐ„์ด ๊ฝค ๊ฑธ๋ฆฐ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ ‡๊ฒŒ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ค๊ฐ€ ์•„๋ž˜์™€ ๊ฐ™์€ ํ’€์ด๋ฅผ ๋ณด์•˜์Šต๋‹ˆ๋‹ค.

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

์ด์ „์— map์„ ์‚ฌ์šฉํ•˜์—ฌ ํ’€์—ˆ๋˜ ํ’€์ด๋ณด๋‹ค ์‹œ๊ฐ„์ด ๋‘๋ฐฐ๋‚˜ ์ ๊ฒŒ ๊ฑธ๋ ธ๊ณ , ๋ฉ”๋ชจ๋ฆฌ๋„ ํ›จ์”ฌ ๋œ ์žก์•„๋จน์€ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํ’€์ด๋ฅผ ๋ณด๋ฉด ๋…ผ๋ฆฌ์—ฐ์‚ฐ์ž๋ฅผ ์ด์šฉํ•ด์„œ ํ‘ผ ํ’€์ด์ธ๋ฐ ๊ทธ ๋ฐฉ๋ฒ•์ด ์‹ ๋ฐ•ํ–ˆ์Šต๋‹ˆ๋‹ค. XOR ์—ฐ์‚ฐ์ธ ^ ๋น„ํŠธ์—ฐ์‚ฐ์ž๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ์ง„๋ฆฌํ‘œ๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

INPUT OUTPUT
A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0

 

์ด ์›๋ฆฌ๋ฅผ ์ด์šฉํ•ด์„œ ๋ฐฐ์—ด์— ๊ฐ’์ด [4,1,2,1,2]๊ฐ€ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๊ณ  ans^=arr [i]; ๊ตฌ๋ฌธ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค๊ณ  ํ•ด๋ด…์‹œ๋‹ค.

์ฒ˜์Œ ans = 4๊ฐ€๋ฉ๋‹ˆ๋‹ค.

๊ทธ๋‹ค์Œ์€ 0100^0001 = 0101 ์ด ๋˜์–ด ans = 5์ด ๋˜๊ณ ,

๋‹ค์Œ, 0101 ^ 0010 = 0111, ans=7,  

๋‹ค์Œ, 0111 ^ 0001 = 0110, ans= 6,

๋‹ค์Œ, 0110 ^0010 = 0100 , ans=4 ๊ฐ€ ๋˜์–ด ์ค‘๋ณต๋˜์ง€ ์•Š์€ 4์˜ ๊ฐ’์„ ๋ฝ‘์•„๋‚ด๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๊ฒฐ๊ตญ ๋˜‘๊ฐ™์€ ๊ฐ’์— ๋Œ€ํ•ด ^ ์—ฐ์‚ฐ์„ ๋‘ ๋ฒˆ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ๋˜๋ฉด, ์›๋ž˜์˜ ๊ฐ’์œผ๋กœ ๋Œ์•„์˜ค๋Š” ์›๋ฆฌ๋ฅผ ์ด์šฉํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค. 

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Majority Element  (0) 2021.11.28
[Leetcode,c++] Network Delay Time  (0) 2021.11.22
[Leetcode,c++] Valid Anagram  (0) 2021.11.20
[Leetcode,c++] Combination Sum II  (0) 2021.11.16
[Leetcode,c++] Subsets II  (0) 2021.11.15
[Leetcode,c++] Rotate Image  (0) 2021.11.15

๋Œ“๊ธ€