GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — LeetCode/Dynamic_Programming/376.Wiggle-Subsequence at master · black128/LeetCode

Expand file tree

/

376.Wiggle-Subsequence

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
 
 
/

376.Wiggle-Subsequence

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
376.Wiggle-Subsequence_DP.cpp
376.Wiggle-Subsequence_DP.cpp
 
 
376.Wiggle-Subsequence_v1.cpp
376.Wiggle-Subsequence_v1.cpp
 
 
Readme.md
Readme.md
 
 

Readme.md

Outline

376.Wiggle-Subsequence

解法1:贪心

我们将整个数组的函数曲线画出来,其实只要数有多少个“拐点”,就是最后的答案了。道理也很简单,最长的wiggle序列,一定会是尽量充分利用所有的拐点。

这里特别要注意的是如果有两个相邻的点相同怎么处理?算是“拐点”吗?不一定。我们只有定义某点斜率前后的正负号的改变才是算拐点。举个例子,当nums[i]>nums[i-1]的时候,这中间的斜率k为正;但如果之前的nums[i-2]==nums[i-1]的话,我们无法判定斜率是否改变了符号。因此我们需要记录下nums[i-1]之前最近的一个非零斜率k',查看它的正负号再与当前的k作比较。所以我们每次更新某两个相邻点之间的斜率的时候,如果是零,我们认为这段斜率依然保持为之前最近的一个非零斜率。

核心代码如下

        for (int i=1; i<nums.size(); i++)
        {
            int dir_pre = dir;
            
            if (nums[i]-nums[i-1]>0)
                dir = 1;
            else if (nums[i]-nums[i-1]<0)
                dir = -1;
            else   
                dir = dir_pre;

            if (dir!=dir_pre)
                ret++;
        }

解法2:DP

设计两个状态变量:p表示截止目前为止,最后一个元素是上升趋势的最长wiggle子序列;q表示截止目前为止,最后一个元素时下降趋势的最长wiggle子序列。

每查看一个数字,尝试更新两个变量p和q。当nums[i]比nums[i-1]大时,意味着q对应的序列之后又出现了一个上升段,说明可以更新p,即p=q+1。当nums[i]比nums[i-1]小时,意味着p对应的序列之后又出现了一个下降段,说明可以更新q,即p=q+1

因为无法确定最长wiggle序列的最后一段是上升还是下降,因此最后的答案是在p和q之间选最大值。

Leetcode Link

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.