Single number Leetcode Java

Source: Internet
Author: User

Problem Description:

Given an array of integers, every element appears twice except for one. Find the single one.

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

problem Analysis: linear time complexity is required, and it is best not to use extra space.

One, bit operation

An XOR operation that returns 1 only if the two bits are different. If the two numbers are the same, the XOR operation will return 0.

The nums contains only a single number, so, using an XOR operation, the last thing you get is the number you are seeking.

public int singlenumber (int[] nums) {

int single = 0;

for (int i = 0; i < nums.length; i + +)

Single = single ^ nums[i];

return single;

}

Second, HashSet

Compared to Hashtable,hashmap stored key-value key-value pairs, hashset directly manipulate objects and do not allow duplicate elements to be stored.

public int singlenumber (int[] nums) {

hashset<integer> set = new hashset<integer> ();

for (int i = 0; i < nums.length; i + +)

if (!set.add (Nums[i]))//Add Duplicate

Set.remove (Nums[i]); Delete duplicate elements

iterator<integer> Iterator = Set.iterator (); Iterator, traversing set

return Iterator.next ();

}

Single number Leetcode Java

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.