zoukankan      html  css  js  c++  java
  • 程序员面试金典-面试题 10.11. 峰与谷

    题目:

    在一个整数数组中,“峰”是大于或等于相邻整数的元素,相应地,“谷”是小于或等于相邻整数的元素。例如,在数组{5, 8, 6, 2, 3, 4, 6}中,{8, 6}是峰, {5, 2}是谷。现在给定一个整数数组,将该数组按峰与谷的交替顺序排序。

    示例:

    输入: [5, 3, 1, 2, 3]
    输出: [5, 1, 3, 2, 3]
    提示:

    nums.length <= 10000

    分析:

    以峰与谷交替的顺序来看,当为峰的位置,如果比前一个元素小,就和前一个元素交换。为谷的位置,如果比前一个元素大的话,就和前一个元素交换。

    程序:

    class Solution {
        public void wiggleSort(int[] nums) {
            for(int i = 1; i < nums.length; ++i){
                if(i % 2 == 0){
                    if(nums[i] < nums[i-1])
                        swap(nums, i, i-1);
                }else{
                    if(nums[i] > nums[i-1])
                        swap(nums, i, i-1);
                }
            }
        }
        private void swap(int[] nums, int i, int j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
  • 相关阅读:
    U-Boot新手入门
    安装交叉编译工具
    Makefile 工程管理
    gcc基本用法
    poj 3264 Balanced Lineup
    hdoj 1166 敌兵布阵
    poj 1363 Rails
    poj 1028 Web Navigation
    zoj 3621 Factorial Problem in Base K
    poj1861最小生成树
  • 原文地址:https://www.cnblogs.com/silentteller/p/12491567.html
Copyright © 2011-2022 走看看