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];}