前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Array - 508. Wiggle Sort

Array - 508. Wiggle Sort

作者头像
ppxai
发布2020-09-23 17:09:02
3940
发布2020-09-23 17:09:02
举报
文章被收录于专栏:皮皮星球皮皮星球皮皮星球

508. Wiggle Sort

Given an unsorted array nums, reorder it in-place such that

nums[0] <= nums[1] >= nums[2] <= nums[3]....

Example

Example 1:

Input: [3, 5, 2, 1, 6, 4]
Output: [1, 6, 2, 5, 3, 4]
Explanation: This question may have multiple answers, and [2, 6, 1, 5, 3, 4] is also ok. 

Example 2:

Input: [1, 2, 3, 4]
Output: [2, 1, 4, 3] 

Notice

Please complete the problem in-place.

思路:

仔细分析输出数组,可以发现下标索引为奇数的数是极大值点,下标索引是偶数的是极小值点,只要遍历数组的时候,移动相邻两个数,就可以。

代码:

java:

public class Solution {
    /*
     * @param nums: A list of integers
     * @return: nothing
     */
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length <= 1) return;
        
        for (int i = 1; i < nums.length; i++) {
            if (i % 2 == 1){
                if (nums[i - 1] > nums[i]) swap(nums, i - 1, i);
            } else {
                if (nums[i - 1] < nums[i]) swap(nums, i - 1, i);
            }
        }
        
    }
    
    private void swap(int[] nums, int i, int j ){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年06月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example
  • Notice
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档