码迷,mamicode.com
首页 > 其他好文 > 详细

136. Single Number

时间:2019-02-10 00:06:28      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:near   except   amp   有一个   note   main   内容   ips   app   

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

标签:near   except   amp   有一个   note   main   内容   ips   app   

原文地址:https://www.cnblogs.com/17bdw/p/10358167.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!