LeetCode—376. Wiggle Subsequence—Analysis and Code (Java)

LeetCode—376. Wiggle Subsequence [Wiggle Subsequence]—Analysis and Code [Java]

1. Title

If the difference between consecutive numbers alternates strictly between positive and negative numbers, the sequence of numbers is called a wobble sequence. The first difference (if it exists) may be positive or negative. A sequence of less than two elements is also a wobble sequence.
For example, [1,7,4,9,2,5] is a swing sequence, because the difference (6,-3,5,-7,3) is alternating between positive and negative. On the contrary, [1,4,7,2,5] and [1,7,4,5,5] are not swing sequences. The first sequence is because its first two differences are both positive. The second sequence It is because its last difference is zero.
Given an integer sequence, return the length of the longest subsequence as a wobble sequence. The sub-sequence is obtained by deleting some (or not deleting) elements from the original sequence, and the remaining elements maintain their original order.

Example 1:

输入: [1,7,4,9,2,5]
输出: 6 
解释: 整个序列均为摆动序列。

Example 2:

输入: [1,17,5,10,13,15,10,5,16,8]
输出: 7
解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。

Example 3:

输入: [1,2,3,4,5,6,7,8,9]
输出: 2

Advanced:
Can you complete this problem with O(n) time complexity?

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/wiggle-subsequence
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Greedy Algorithm

(1) Thinking

Because the elements in the original sequence can be deleted, you only need to delete elements whose difference is continuously positive or negative, and the rest is the swing sequence.
The goal of this question is to count the length of the longest subsequence, so there is no need to delete operations in the actual array, just count the number directly when traversing.

(2) Code

class Solution {
    
    
    public int wiggleMaxLength(int[] nums) {
    
    
        if (nums.length < 2)
            return nums.length;
        
        int i = 1;
        while (i < nums.length && nums[i - 1] == nums[i])
            i++;
        if (i == nums.length)
            return 1;
        
        int ans = 2;
        boolean posi = (nums[i] > nums[i - 1]) ? true : false;
        for (; i < nums.length; i++)
            if ((posi == true && nums[i] < nums[i - 1]) || (posi == false && nums[i] > nums[i - 1])) {
    
    
                posi = !posi;
                ans++;
            }

        return ans;
    }
}

(3) Results

Execution time: 0 ms, beating 100.00% of users
in all Java submissions ; memory consumption: 35.7 MB, beating 93.68% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112853452