LintCode : 1164. Wiggle Subsequence

描述

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

要找出摇摆最长的序列

个人思路:因为是摇摆序列,所以i位置的数和i-1位置的数的差与i位置的数和i+1位置的数的差一定是正负相间的,所以先遍历一次,得到第i个数和第i-1个数的差值情况,采取的贪心策略就是,遍历得到的数组(也是两根指针的运用),寻找正负相间的最长长度

 public int wiggleMaxLength(int[] nums) {
        // Write your code here
        int len = nums.length;
        List<Integer> list = new ArrayList<>(len);

        for (int i = 1; i < len; i++) {
            list.add(nums[i] - nums[i-1]);
        }

        int maxLen = 2;
        int index = 0;
        for (int i = 1; i < list.size(); i++) {
            if (list.get(index) == 0) {
                index++;
            }
            if(list.get(i)*list.get(index) < 0){
                maxLen++;
                //System.out.println(i+" "+index);
                index = i;
            }
        }

        return maxLen;

    }

dalao思路:采取的贪心策略是,如果第i个数比i-1大,是上升,则上升 = 下降+1,如果小,是下降,则下降 = 上升+1,最后两者取最大值(多么优雅的做法)

public int wiggleMaxLength(int[] nums) {
        // Write your code here
        int up = 1, down = 1;
        for (int i=1;i<nums.length;i++) {
            if (nums[i] > nums[i-1]) {
                up = down + 1;
            } else if (nums[i] < nums[i-1]) {
                down = up + 1;
            }
        }
        return Math.max(up, down);
    }

summary:dalao的思路总是考虑结合题目条件考虑当前遍历时的最优解,就是在另外一个趋势的基础上+1

猜你喜欢

转载自blog.csdn.net/qq_38702697/article/details/82762523
今日推荐