LeetCode clocking in (1)

Today’s new round of punch-in, let’s start with simple questions.

Array split I
https://leetcode-cn.com/problems/array-partition-i/submissions/

It's a very interesting greedy question, with very little difficulty.
But the process of proving his can be carried out using dynamic programming methods.
But for this dynamic planning, we started thinking from the most complicated situation to the simplest situation.

Assuming that this is an array of 2n elements in a sorted sequence, we consider that the largest number that can be obtained each time must be the second largest number less than or equal to the sorted elements. The greedy strategy is used to obtain the largest number possible. Next, combine the largest number of the sequence into a tuple.

At this time, the elements in the sequence that have been made up into tuples are discarded, and the remaining elements form an array of 2 (n-1) elements. Can be recursively in sequence.

Code:

class Solution {
    
    
public:
    int arrayPairSum(vector<int>& nums) {
    
    
        int n=size(nums);        
        sort(nums.begin(),nums.end());
        int  sum=0;
        for(int i=0;i<n;i++){
    
    
            if(i%2==0)
            sum+=nums[i];
        }
        return sum;
    }
};

The maximum number of consecutive ones:
https://leetcode-cn.com/problems/max-consecutive-ones/
Ideas:
1. If you want to find a continuum, there must be a head and a tail, so if you update like this, it will be more expensive than the cumulative general algorithm It looks beautiful and easy to think of.
2. Or directly simulate calculation.

class Solution {
    
    
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
    
    
        int start=-1;
        int n=size(nums);
        int now=0;
        int res=0;
        int temp=0;
        for(int i=0;i<n;i++){
    
    
            if(nums[i]) continue;
            else{
    
    
                now=i;
                temp=now-start-1;
                start=now;
                if(temp>res) res=temp;
            }
        }
        if(nums[n-1]!=0&&n-start-1>res) res=n-start-1;
        return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_47741017/article/details/113823415