LeetCode 324. Wiggle Sort II A(i)=(2*i+1)%(n|1) 荷兰国旗问题 & 376. Wiggle Subsequence & 280

本文探讨了如何在O(n)时间内实现数组的波动排序,即nums[0] <= nums[1] >= nums[2] <= nums[3]...通过巧妙地利用荷兰国旗问题的思路,文章详细介绍了寻找中位数并重新排列的过程,同时提供了Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

Example 1:

Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].

Example 2:

Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

------------------------------------------------------------------------

This problem is really hard with O(n) time and O(1) space restriction. However, it's not hard to find median with O(n). But what's next??? At least two problems should be understood:

  • How could we arrange all medians in the middle of array in O(n) time complexity? That's the popular Netherlands flag problem.
  • Maybe duplicates same with median exist. For nums <= median, median is the largest one; for nums>= median, median is the smallest one. We should split medians into starting positions and ending positions to avoid medians "meet". The virtual indexes examples are:
  • Accessing A(0) actually accesses nums[1].
    Accessing A(1) actually accesses nums[3].
    Accessing A(2) actually accesses nums[5].
    Accessing A(3) actually accesses nums[7].
    Accessing A(4) actually accesses nums[9].
    Accessing A(5) actually accesses nums[0].
    Accessing A(6) actually accesses nums[2].
    Accessing A(7) actually accesses nums[4].
    Accessing A(8) actually accesses nums[6].
    Accessing A(9) actually accesses nums[8]

How could we write out the right indexes relationship. Maybe just remember it by now (A[i] = (2*i+1)%(n|1), n is the array length)...The following are the codes:

class Solution:
    def find_kth(self, nums, start, end, kth):
        i, j, pivot = start, end, nums[start + ((end - start) >> 1)]
        while (i <= j):
            while (nums[i] < pivot):
                i += 1
            while (nums[j] > pivot):
                j -= 1
            if (i <= j):
                nums[i], nums[j] = nums[j], nums[i]
                i, j = i + 1, j - 1
        if (i - 1 == j + 1 and i - start == kth):
            return nums[i-1]
        elif (i - start >= kth): #bug1: >= instead of >
            return self.find_kth(nums, start, i - 1, kth)
        else:
            return self.find_kth(nums, i, end, kth - (i - start))

    def A(self, i, n):
        return (2 * i + 1) % (n | 1)

    def wiggleSort(self, nums) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        kth = l // 2 if l % 2 == 0 else (l >> 1) + 1
        k_val = self.find_kth(nums, 0, l - 1, kth)

        i, j, k = 0, 0, l - 1
        while (j <= k):
            if (nums[self.A(j, l)] < k_val):
                nums[self.A(j, l)], nums[self.A(k, l)] = nums[self.A(k, l)], nums[self.A(j, l)]
                k -= 1
            elif (nums[self.A(j, l)] > k_val):
                nums[self.A(j, l)], nums[self.A(i, l)] = nums[self.A(i, l)], nums[self.A(j, l)]
                i, j = i + 1, j + 1
            else:
                j += 1

s = Solution()
nums = [1, 5, 1, 1, 6, 4]
s.wiggleSort(nums)
print(nums)

-------------------------------------------------------------

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.

Example 1:

Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.

Example 2:

Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].

Example 3:

Input: [1,2,3,4,5,6,7,8,9]
Output: 2

Follow up:
Can you do it in O(n) time?

---------------------------------------------------------------

Stateful DP

class Solution:
    def wiggleMaxLength(self, nums) -> int:
        l = len(nums)
        if (l <= 0):
            return 0
        # increasing end, decreasing end, increasing length, decreasing length
        ie, de, il, dl = nums[0], nums[0], 1, 1
        for i in range(1, l):
            nie, nde, nil, ndl = ie, de, il, dl
            if (nums[i] > de and dl + 1 > il):
                nil, nie = dl + 1, nums[i]
            if (nums[i] < ie and il + 1 > dl):
                ndl, nde = il + 1, nums[i]
            if (nums[i] > ie):
                nie = nums[i]
            if (nums[i] < de):
                nde = nums[i]
            ie, de, il, dl = nie, nde, nil, ndl
        return max(il, dl)

----------------------------------------------------------------

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

--------------------------------------------------------------------------

= makes the problem easy:

// Time Complexity O(n)
class Solution {
public:
    void wiggleSort(vector<int> &nums) {
        if (nums.size() <= 1) return;
        for (int i = 1; i < nums.size(); ++i) {
            if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) {
                swap(nums[i], nums[i - 1]);
            }
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值