"Leetcode" Single Number Problem solving report (Java & Python) __leetcode

Source: Internet
Author: User
Tags bitwise
"Leetcode" single Number Problem solving report (Java & Python)

[Leetcode]

Https://leetcode.com/problems/single-number/Total accepted:183838 Total submissions:348610 difficulty:easy Question

Given an array of integers, every element appears twice for one. Find is single one.
Note:
Your algorithm should have a linear runtime. Could you implement it without using extra memory? Ways

I was too weak, the problem of bit arithmetic is not basic. Read the high vote answer to understand can do so.

Use XOR or operation.

XOR is an operation that can be exchanged in order, that is, it is independent of the order of the elements, or that they are equal to 0, 0 different or others equal to others. So

We use the bitwise XOR to solve this problem:

Have to know the bitwise XOR in Java

1.0 ^ n = n
2. N ^ n = 0

So ..... If N is the single number

N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ NX ^ N

= (n1^n1) ^ (n2^n2) ^..............^ (nx^nx) ^ N

= 0 ^ 0 ^ .... ^ 0 ^ N

= N

public class Solution {public
    int singlenumber (int[] nums) {
        int returnnum=0;
        for (int i=0; i<nums.length; i++) {
            returnnum ^=nums[i];
        }
        Return Returnnum
    }
}

Ac:1ms

Two brushes python

Class Solution (object):
    def singlenumber (self, Nums): ""
        "
        : Type Nums:list[int]
        : Rtype:int
        " "" Return to
        reduce (lambda x, y:x ^ y, nums)
Date

January 7, 2017
March 14, 2018 – Hawking dies

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.