136. Single Number

Posted 17bdw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了136. Single Number相关的知识,希望对你有一定的参考价值。

Algorithm

Single Number

https://leetcode.com/problems/single-number/

1)problem

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

2)answer

数组中其他数出现两次,仅有一个出现一次的。逐个字符进行异或来,当某个数字出现第二次时候数字就归为0。二进制计算逻辑如下:

  二进制            异或      下一次的异或值   实际值    
4 ==> 100  ==>  100 ^ 000      = 100        = 4
1 ==> 001  ==>  001 ^ 100      = 101        = 5
2 ==> 010  ==>  010 ^ 101      = 111        = 7
1 ==> 001  ==>  001 ^ 111      = 110        = 6
2 ==> 010  ==>  010 ^ 110      = 100        = 4

3)solution

Cpp:

#include <stdio.h>
#include <vector>
using std::vector;


class Solution {
public:
    int singleNumber(vector<int>& nums) {
        
        int aNum = 0;
        for (int i = 0; i < nums.size(); i++) {
            aNum ^= nums[i];
        }
        return aNum;
    }
};

int main() 
{

    // 使用内容
    Solution nSolution;
    vector<int> nums;

    nums.push_back(2);
    nums.push_back(1);
    nums.push_back(2);
    nSolution.singleNumber(nums);
    return 0;
}

Python:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        r_nums = 0
        for num in nums:
            r_nums ^= num
        return r_nums

4)总结

Tips:按tags刷会比较有效率。

  • String

https://leetcode.com/problemset/all/?topicSlugs=string

https://leetcode.com/problems/unique-email-addresses

https://leetcode.com/problems/to-lower-case

  • HASH Tables

https://leetcode.com/problems/jewels-and-stones

https://leetcode.com/problems/single-number

以上是关于136. Single Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode之136. Single Number

136.Single Number

LeetCode136 Single Number, LeetCode137 Single Number II, LeetCode260 Single Number III

136. Single Number

136. Single Number

136. Single Number