Single Number II

Source: Internet
Author: User

Single Number II

 

 

Given an array of integers, every element appears three times must t for one. Find that single one.

Note:
Your algorithm shocould have a linear runtime complexity. cocould you implement it without using extra memory?


Ideas:

(1) given an integer array, each of the other elements appears three times in addition to one element, to find the element that appears once.

(2) This question is similar to that of Single Number. However, in Single Number, only one element appears once, And the rest appear twice, in this case, you can simply use the '^' symbol for processing. However, due to limited technology, there is no simple method yet. The method below is feasible, but it will take up extra space.

(3) The idea of solving this problem in this article is: create a Map to save the number of occurrences of elements and elements in the array. During the process of traversing the array, all the numbers that appear are saved to the Map, here, you also need to perform a step-by-step filtering operation, that is, every time the retrieved element corresponds to a value greater than 1 in the Map, the value is saved to the filter List, remove the value from the Map. In subsequent traversal, if the retrieved value exists in the filter List, the next element is skipped, the last remaining element in the Map is the one that appears once.

(4) I hope this article will help you.

 

 

The algorithm code is implemented as follows:

 

/** * @author liqq */public int singleNumber(int[] A) {if (A == null || A.length == 0)return -1;if (A != null && A.length == 1)return A[0];Map
 
   maps = new HashMap
  
   ();List
   
     filter = new ArrayList
    
     ();for (int i = 0; i < A.length; i++) {if (i == 0) {maps.put(A[i], 1);} else {if (!filter.contains(A[i])) {if (maps.get(A[i]) == null) {maps.put(A[i], 1);} else {maps.put(A[i], maps.get(A[i]) + 1);}if (maps.get(A[i]) > 1) {maps.remove(A[i]);filter.add(A[i]);}}}}return maps.keySet().toArray(new Integer[0])[0];}
    
   
  
 


 

 

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.