The way to solve the problem of force deduction ----- traversal of array

Keywords: Algorithm leetcode

Refer to the brushing order: Force deduction brushing sequence

This article makes a self summary, summarizes their own ideas when doing problems and the official ideas for solving problems.

485 maximum number of consecutive 1


It's a very simple question, so there's nothing to say. Put a code.

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int time = 0;
        int max = 0;
        for(int i = 0;i<nums.length;i++){
            if(nums[i] == 1){
                time++;
                if(max<=time){
                    max = time;
                }
            }
            else {

                time = 0;
            }
        }
        return max;
    }
}

495 Timo attack


Own ideas:
I've really thought about this topic. I've always wanted to find a law that can directly calculate the results of several situations. I thought I could take some short cuts in the beginning and end time. Later, I found that what I thought was too complicated. This problem is mainly based on drawing, which is the same as the mathematical induction in childhood. I think we should start from the simple idea first. The simplest idea may be the best.
There are two situations: one is (start attack time + attack duration) < = next start attack time, that is, when the second attack is over, the last attack is over. In this case, the attack duration is directly +; Second, the last attack has not ended, as shown in the figure. The extra time of the second attack is 2-1. It's the same with more paintings.

class Solution {
    public int findPoisonedDuration(int[] timeSeries, int duration) {
        int time=duration;
        for(int i=0;i<timeSeries.length-1;i++){
            if(timeSeries[i]+duration <= timeSeries[i+1]){
                time+=duration;
            }
            else{
                time+=timeSeries[i+1]-timeSeries[i];
            }
        }
        return time;
    }
}

Official thinking:
After reading, the official problem-solving ideas are the same, but the codes are different.

class Solution {
    public int findPoisonedDuration(int[] timeSeries, int duration) {
        int n = timeSeries.length;
        if (n == 0) return 0;

        int total = 0;
        for(int i = 0; i < n - 1; ++i)
          total += Math.min(timeSeries[i + 1] - timeSeries[i], duration);
        return total + duration;
    }
}

Author: LeetCode
 Link: https://leetcode-cn.com/problems/teemo-attacking/solution/ti-mo-gong-ji-by-leetcode/
Source: force buckle( LeetCode)

414 the third largest number


Own ideas:
It's too complicated to think about. First put the numbers of the array into a set, and then put them into the list to order. Finally, if the length of the list is greater than or equal to 3, the third number will be output; otherwise, the maximum number will be output. Just looking at this idea, you can know that the time and space complexity of this algorithm is very large.

class Solution {
    public int thirdMax(int[] nums) {
        int n = nums.length;
        List temp = new LinkedList();
        Set changes = new HashSet();
        for(int i=0;i<n;i++){
            changes.add(nums[i]);
        }
        for(Object change:changes){
            temp.add(change);
        }
        temp.sort(Comparator.reverseOrder());
        if(temp.size()>=3){
            return temp.get(2).hashCode();
        }
        else return temp.get(0).hashCode();
    }
}

Official idea:
The first is the method of ordered set, which uses TreeSet to store numbers. When the length of the set is greater than 3, delete the smallest, which can ensure that the smallest is always the third largest. Learned the method of ordered set.

class Solution {
    public int thirdMax(int[] nums) {
        TreeSet<Integer> s = new TreeSet<Integer>();
        for (int num : nums) {
            s.add(num);
            if (s.size() > 3) {
                s.remove(s.first());
            }
        }
        return s.size() == 3 ? s.first() : s.last();
    }
}

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/third-maximum-number/solution/di-san-da-de-shu-by-leetcode-solution-h3sp/
Source: force buckle( LeetCode)

Another method is to set three numbers: first, second and third, which respectively represent the first, second and third largest numbers. Traverse the array and change the number of these three flags during the traversal. At the beginning, set the three numbers to be smaller than the minimum value of the array value. If third changes, output third, otherwise output first.

    public void thinkTest(){
        long INF = (long)Math.pow(-2,31)-1;
        int nums[] = {1,3,2,2};
        long first,second,third;
        first=second=third=INF;
        int n = nums.length;
        for(int i=0;i<n;i++){
            if(nums[i]>first){
                third=second;
                second=first;
                first=nums[i];
            }
            if(nums[i]>second && nums[i]<first){
                third=second;
                second=nums[i];
            }
            if(nums[i]>third && nums[i]<second ){
                third=nums[i];
            }

        }
        if(third!=INF){
            System.out.println(third);
        }
        else System.out.println(first);
    }

628 maximum product of three numbers


Own ideas:
I've been stuck with this problem card for a long time. I wanted to sort by absolute value, and then I found that I couldn't find a rule. Later, I really couldn't think of it. I read the official idea of solving the problem. I sorted it directly according to the size and divided it into three cases: all positive, all negative, positive and negative. The final result of these three cases is the product of three maxima or the multiplication of one maxima and two minima Ji. Sure enough, I still need to calm down. Don't worry, write it down.

    public void mytest(){
        int[] nums = {-100,-2,-3,1};
        int n=nums.length;
        int max;
        for(int i=0;i<n-1;i++){
            max=nums[i];
            for(int j = i+1;j<n;j++){
                if(max< nums[j]){
                    int temp;
                    temp=max;
                    max = nums[j];
                    nums[j]=temp;
                }
            }
            nums[i] = max;
        }
        System.out.println(Math.max(nums[0]*nums[1]*nums[2],nums[0]*nums[n-1]*nums[n-2]));
    }

I read the code written by myself. Then I read the official code. It's so simple! I've learned!
Official idea:

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        return Math.max(nums[0] * nums[1] * nums[n - 1], nums[n - 3] * nums[n - 2] * nums[n - 1]);
    }
}

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/maximum-product-of-three-numbers/solution/san-ge-shu-de-zui-da-cheng-ji-by-leetcod-t9sb/
Source: force buckle( LeetCode)

The other method is similar to 414. Because only the first three largest numbers and the two smallest numbers are involved. Just find these numbers.

class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        // The smallest and second smallest
        int min1 = INT_MAX, min2 = INT_MAX;
        // The largest, second and third largest
        int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;

        for (int x: nums) {
            if (x < min1) {
                min2 = min1;
                min1 = x;
            } else if (x < min2) {
                min2 = x;
            }

            if (x > max1) {
                max3 = max2;
                max2 = max1;
                max1 = x;
            } else if (x > max2) {
                max3 = max2;
                max2 = x;
            } else if (x > max3) {
                max3 = x;
            }
        }

        return max(min1 * min2 * max1, max1 * max2 * max3);
    }
};

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/maximum-product-of-three-numbers/solution/san-ge-shu-de-zui-da-cheng-ji-by-leetcod-t9sb/
Source: force buckle( LeetCode)

Summary:
The traversal of arrays is not difficult. It is found that sometimes using if statement can be changed to using max method, which seems to be more convenient, and you can learn when doing problems in the future. In addition, when doing problems, you should calm down and think blindly in your mind. You need to pick up a pen to write. You can't always think of becoming fat in one bite. You need to start from the simplest , perhaps the simplest is the best.

Posted by eskimowned on Wed, 06 Oct 2021 14:21:40 -0700