Title: One element in an integer array appears more than half the length of the array, try to design an algorithm that is as efficient as possible in time to find this element. Requirements:
(1) The basic design idea of the algorithm is given.
(2) According to the design idea, using C or C + + or Java language to describe the algorithm, the key points to give a comment.
(3) Describe the time complexity and space complexity of the algorithm you are designing.
(1) Basic design idea: A number appears more than half of the length, then we can think that the number must appear more than the sum of the number of all other numbers appear. The steps of the algorithm are as follows: ① array is data[] and the array length is n,i=1. Currentaxis=data[0],currentnum=1. ② when Data[i]==currentaxis, currentnum++, turn to ④, otherwise turn to ③. ③currentnum--, when Currentnum==0, Currentaxis=data[i]. ④ when I==data.length, turn to ⑤; otherwise, i++, turn ②;⑤ return Currentaxis.
(2) Algorithm implementation:
#include <iostream>using namespacestd;intFuntionintData[],intlength) { intCurrentaxis;//assume the location of the requested element intCurrentnum =0;//the number of variables required for the element for(inti =0; i<length;i++) { if(Currentnum = =0){ //if the requested element does not yet appear, set the required element to the element that is now being comparedcurrentaxis=Data[i]; Currentnum=1; } Else { if(currentaxis==Data[i])//The hypothetical result is different from the comparison element, assuming that the number of results increases by 1, otherwise minus 1currentnum++; ElseCurrentnum--; } } returnCurrentaxis;//returns the position of the final result. }intMain () {intarr[]={1,2,3,2,5,6,2,2,3,2,2,4}; cout<<"number="<<funtion (arr, A) <<Endl; return 0;}
(3) The time complexity is O (n). Space complexity O (1).
The most straightforward way to "solve another" is to sort each number. You can then output the largest number of occurrences, but the sorting time is the fastest and the most complex is O (nlog2n).
In an integer array where one element appears more than half the length of the array, try to design an algorithm that is as efficient as possible in time to find this element.