返回介绍

lcci / 10.11.Peaks and Valleys / README_EN

发布于 2024-06-17 01:04:43 字数 2582 浏览 0 评论 0 收藏 0

10.11. Peaks and Valleys

中文文档

Description

In an array of integers, a "peak" is an element which is greater than or equal to the adjacent integers and a "valley" is an element which is less than or equal to the adjacent inte­gers. For example, in the array {5, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {5, 2} are valleys. Given an array of integers, sort the array into an alternating sequence of peaks and valleys.

Example:


Input: [5, 3, 1, 2, 3]

Output: [5, 1, 3, 2, 3]

Note:

  • nums.length <= 10000

Solutions

Solution 1: Sorting

We first sort the array, and then traverse the array and swap the elements at even indices with their next element.

The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array.

class Solution:
  def wiggleSort(self, nums: List[int]) -> None:
    nums.sort()
    for i in range(0, len(nums), 2):
      nums[i : i + 2] = nums[i : i + 2][::-1]
class Solution {
  public void wiggleSort(int[] nums) {
    Arrays.sort(nums);
    int n = nums.length;
    for (int i = 0; i < n - 1; i += 2) {
      int t = nums[i];
      nums[i] = nums[i + 1];
      nums[i + 1] = t;
    }
  }
}
class Solution {
public:
  void wiggleSort(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int n = nums.size();
    for (int i = 0; i < n - 1; i += 2) {
      swap(nums[i], nums[i + 1]);
    }
  }
};
func wiggleSort(nums []int) {
  sort.Ints(nums)
  for i := 0; i < len(nums)-1; i += 2 {
    nums[i], nums[i+1] = nums[i+1], nums[i]
  }
}
/**
 Do not return anything, modify nums in-place instead.
 */
function wiggleSort(nums: number[]): void {
  nums.sort((a, b) => a - b);
  const n = nums.length;
  for (let i = 0; i < n - 1; i += 2) {
    [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]];
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文