zoukankan      html  css  js  c++  java
  • 280. Wiggle Sort

    package LeetCode_280
    
    /**
     * 280. Wiggle Sort
     * (locked by leetcode)
     * https://www.lintcode.com/problem/wiggle-sort/description
     *
     * Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
    
    Example:
    Input: nums = [3,5,2,1,6,4]
    Output: One possible answer is [3,5,1,6,2,4]
    
    Please complete the problem in-place.
     * */
    class Solution {
        fun wiggleSort(nums: IntArray) {
            for (i in 1 until nums.size) {
                //follow by this situation: nums[0] <= nums[1] >= nums[2] <= nums[3]
                //so if i is even and and nums[i] > nums[i-1], swap this two num and
                //if if i is odd and nums[i] < nums[i-1], swap this two num also
                if (i % 2 == 0 && nums[i] > nums[i - 1] || i % 2 != 0 && nums[i] < nums[i - 1]) {
                    swap(nums, i, i - 1)
                }
            }
        }
    
        private fun swap(nums: IntArray, i: Int, j: Int) {
            val temp = nums[i]
            nums[i] = nums[j]
            nums[j] = temp
        }
    }
  • 相关阅读:
    rsync特性
    01 什么是爬虫
    celery的使用
    redis的使用
    GIT使用大全
    多项式的高级运算
    SP1557 GSS2
    题解 CF997E 【Good Subsegments】
    P3920 [WC2014]紫荆花之恋
    题解 P3750 【[六省联考2017]分手是祝愿】
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13110665.html
Copyright © 2011-2022 走看看