面试题 10.11. 峰与谷 ( 思维 )

LeetCode:面试题 10.11. 峰与谷

在这里插入图片描述

有点巧妙, 一开始弄复杂了,想着先把峰和谷存在两个 list 中, 然后再覆盖原数组, 然后发现有些样例的数中既不是峰也不是谷的( 如: n u m s [ i − 1 ] < n u m s [ i ] < n u m s [ i + 1 ] nums[i - 1 ] < nums[i] < nums[i + 1] nums[i1]<nums[i]<nums[i+1]) 这种


解题思路:

假设按照峰-谷-峰的顺序排列数组,那么遍历一遍数组:

(1)如果i为峰的位置,则判断当前位置是否小于前一个位置(前一个为谷),若小于,则交换,大于则不处理。
即: if(nums[i]<nums[i-1]) swap(nums[i],nums[i-1]);

(2)如果i为谷的位置,则判断当前位置是否大于前一个位置(前一个为峰),若大于,则交换,大于则不处理。
即: if(nums[i]>nums[i-1]) swap(nums[i],nums[i-1]);



AC Code

class Solution {
    
    
    public void wiggleSort(int[] nums) {
    
    
        int len = nums.length;
        // 按照 峰谷峰来安排
        for(int i = 1; i < len; 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);
            }
        }
    }

    // 交换
    public void swap(int[] arr, int x, int y){
    
    
        arr[x] = arr[x] ^ arr[y];
        arr[y] = arr[x] ^ arr[y];
        arr[x] = arr[x] ^ arr[y];
    }
}



猜你喜欢

转载自blog.csdn.net/qq_43765535/article/details/112913026