[Jianzhi offer] 39. Numbers that appear more than half of the time in the array

Say before brushing

In the future, in addition to the code and what I want to say , I will shorten the length of the article,

Because too much time is wasted on writing articles!

In fact, it is not difficult to solve the questions, but the difficulty is persistence!

This column is the classic topic of "Jianzhi offer",

And record your understanding and learning process in this blog !

Topic introduction (LINK)

As for the topic, I won’t introduce too much, it’s not very meaningful to copy it, so I’ll just post the link here!

LeetCode link: click here!

NowCoder link: click here!

train of thought/idea

1. Initial Thoughts / Final Thoughts

Idea 1: Map

Define map , use the mapping relationship of <number, number of times> , and finally count the number of occurrences of each character ;

The space complexity of this method is relatively large !

Idea 2: Sorting

For sorting , the number with the most occurrences must be in the middle .

At this time, it is enough to directly output the intermediate value, but if the given array is not the specified array (the number of occurrences does not exceed half),

Just use it!

Then check whether the number of occurrences of the numbers in the middle meets the requirements, which is relatively simple!

Idea 3: Delete

You can think of this idea as cleverly optimized code!

The target data exceeds half of the length of the array, then for the array, we remove two different numbers at the same time, and the last remaining number is the number!

The above logic is cryptic:

Explain: set an initial value (the first element of the array), and then compare it with the following value . If the counter is the same ++, if it is different, --replace the initial value with the value of the next array.

The concept is, "delete" if they are different , and the remaining values ​​will be the most !

This deletion is not a deletion in the true sense, but it is not compared with it!

If there are two remaining, then these two are the same, which is the result. Based on it, return the last remaining number or two to the original array, traverse the array and count the number of occurrences of the number to make a final judgment .

If you still don’t understand, just look at the code I wrote. If you read the code, you won’t be able to call me in the comments or send me a private message. I’ll tell you in a big video!

This is a supplementary point about time complexity: You can see that there are two for loops in the code . Some people wonder if the complexity is n 2 , but no, they actually coexist, and the complexity is still n !

2. Notes

In OJ , JAVA used JDK1.8 , but no import-related packages were added , so you need to import it yourself ;

C++ does not need to write header files, it has been added by default!

Code

1. Define Map implementation code

import java.util.Map;
import java.util.HashMap;

public class Solution {
    
    
    public int MoreThanHalfNum_Solution(int [] array) {
    
    
        if (array == null || array.length == 0) {
    
    
            return 0;
        }
        Map <Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
    
    
            if (map.containsKey(array[i])) {
    
    
                int count = map.get(array[i]);
                count++;
                map.put(array[i], count);// 找到了,次数+1
            }else {
    
    
                map.put(array[i], 1);// 找不到并记录次数为1
            }
            if (map.get(array[i]) > array.length / 2) {
    
     // 验证次数
                return array[i];
            }
        }
        return 0;
    }
}

2. Sorting implementation

//其实这样子也是可以的,更简单!
import java.util.Arrays;

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        if (nums == null || nums.length == 0) {
    
    
            return 0;
        }
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}
//防止给的数组不是规定的数组,可以添加for循环,判断目标的次数!
import java.util.Arrays;

class Solution {
    
    
    public int majorityElement(int[] array) {
    
    
        if (array == null || array.length == 0) {
    
    
            return 0;
        }
        Arrays.sort(array);// 首先排序数组然后找次数
        int target = array[array.length / 2];
        int count = 0;// 计数器
        for (int i = 0; i < array.length; i++) {
    
    
            if (target == array[i]) {
    
    
                count++;
            }
        }
        if (count > array.length / 2) {
    
    
            return target;
        }
        return 0;
    }
}

3. Contrastive deletion method

class Solution {
    
    
    public int majorityElement(int[] array) {
    
    
        if (array == null || array.length == 0) {
    
    
            return 0;
        }
        
        int target = array[0];//设定初始目标值
        int times = 1;//出现次数
        for (int i = 1; i < array.length; i++) {
    
    
            if (times == 0) {
    
    
                target = array[i];
                times = 1;
            }else if (target == array[i]) {
    
    
                times++;
            }else {
    
    
                times--;
            }
        }
        
        times = 0;
        for (int j = 0; j < array.length; j++) {
    
    
            if (target == array[j]) {
    
    
                times++;
            }
        }
        return times > (array.length / 2) ? target : 0;
    }
}

Thank you

During the interview, you answered the solutions of thinking 1 and thinking 2. The interviewer thinks you are okay, but it is still not enough!

In comparison, the third method is more interesting!

For the second method:

In fact, you can just write it directly during the written test, that is, use the ready-made one (the sorting method in Curry), because it is fast!

However, during the interview, you can communicate with the interviewer:

You can ask the interviewer if you want to see my sorting ability or other abilities!

Finally, thank you for reading!

Guess you like

Origin blog.csdn.net/Cbiltps/article/details/122849336