Topic:
If there is a number in the array that appears more than half the length of the array, find this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array of 5, which exceeds half the length of the array, the output 2
Analysis:
Because this number occurs more often than the number of other occurrences, you can consider using stacks to offset the 22.
If you encounter the same, then add, if it is not the same as the end of the stack, then a popup (offset).
So in the end, the last of the remaining stacks is definitely the more than half the number.
Code:
public int getnum (int[] array) {if (array = = null) {throw new RuntimeException ();} stack<integer> stack = new stack<integer> (); for (Integer A:array) {//If the stack is not empty, compare if (!stack.isempty ()) {//AS If the result is the same as the last element of the stack, it is put in if (A = = Stack.peek ()) {Stack.push (a);} else {//is not the same, it pops up Stack.pop ();}} else {//If it is empty, put it directly into Stack.push (a);}} return Stack.pop ();}
The above algorithm uses the on time and the on space
If not stack, with the same idea, with O1 space to achieve
That's 2 numbers to record, the first number to record the elements in the array (equivalent to the last one on the stack)
The second number to record the number of occurrences of the first number.
This completes the above functions with 2 numbers:
Code:
public int getNum2 (int[] array) {if (array = = null) {throw new RuntimeException ();} int tmp = 0;//Here random initialization does not affect, because count is 0int count = 0;for (Integer a:array) {///if same, add if (tmp = = a) {count++;} else {//if the original If there is a value first, subtract one if (Count > 0) {count--;} else {//original count is 0, change tmptmp = A;count = 1;}}} return TMP;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The sword refers to the offer surface question 29-number of occurrences more than half in an array