[Written test programming questions] Day3. (Find the longest continuous number string 69385 in the string) and (23271 the number that appears more than half of the time in the array)

About the author: Hello everyone, I am Weiyang;

Blog Homepage: Weiyang.303

Series of Columns: Written Examination Training Programming Questions

Daily sentence: There is only one time in a person's life to make a difference, and that is now! ! ! !

Article directory

​edit 

foreword

1. Find the longest continuous number string 69385 in the string

topic description

topic analysis

Code

Summarize


 

foreword

1. Find the longest continuous number string 69385 in the string

topic description

Given an array of length n, there is a number in the array that occurs more than half of the length of the array, please find this number. For example: Enter an array [1,2,3,2,2,2,5,4,2] of length 9. Since the number 2 appears 5 times in the array, which exceeds half the length of the array, 2 is output.

Enter a description:

保证数组输入非空,且保证有解

Example:



Topic analysis:

 Problem-solving ideas:

After seeing this question, there are two main ideas:
Idea 1 (common and simple)
  1. First sort our array (no limit to ascending and descending relations);
  2. Find the letter X in the middle;
  3. Then traverse the array; (see how many times this array appears)

Idea 2 (idea of ​​mode elimination)

General idea description:

If the two numbers are not equal, cancel the two numbers;

In the worst case, one mode and one non-mode will be eliminated each time;

Then if there is a mode number, the last number left must be the mode number; but if it is not purely in the mode number, it must not be;

(So ​​this place still has to traverse the array to determine whether the last number is a majority)


Code

Idea one:


Idea 2:


Summarize

 

Guess you like

Origin blog.csdn.net/qq_64861334/article/details/130275144