LeetCode-不重复的数字

1、不重复的数字(LeetCode-136)

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

思路:利用相同数字的异或结果为0这个技巧

class Solution {
public:
    int singleNumber(vector& nums) {
        int val = 0;
        
        for(int i=0; i

2、不重复的数字-II

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99
思路:对于某一bit,如果1的个数为3的倍数,那么说明不重复的数该bit为0;反之为1

class Solution {
public:
    int singleNumber(vector& nums) {
        int ret = 0;
        
        for(int i=0; i>i) & 0x1);
            }
            
            ret |= ((sum%3) << i);   
        }
       
        
        return ret;  
    }
};

3、不重复的数字-III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

思路:所有数据抑或之后,如果某一bit为1,说明在该bit上,不重复的数字一个为0、一个为1;找到一个为1的bit,根据该bit是否为1,将数据分成两部分,那么不重复的数字分别在两个部分里面;对于任意一个部分,除了不重复值之外,其它均是成对出现。


class Solution {
public:
    
    vector singleNumber(vector& nums) {
       
        vector ret;
        int value = 0;
        int a = 0;
        int b = 0;
        
        //先求异或
        for(unsigned int i=0; i



你可能感兴趣的:(LeetCode,OJ算法-位操作)