Java | Leetcode Java题解之第324题摆动排序II

题目:

题解:

java 复制代码
class Solution {
    Random random = new Random();

    public void wiggleSort(int[] nums) {
        int n = nums.length;
        int x = (n + 1) / 2;
        int mid = x - 1;
        int target = findKthLargest(nums, n - mid);
        for (int k = 0, i = 0, j = n - 1; k <= j; k++) {
            if (nums[transAddress(k, n)] > target) {
                while (j > k && nums[transAddress(j, n)] > target) {
                    j--;
                }
                swap(nums, transAddress(k, n), transAddress(j--, n));
            }
            if (nums[transAddress(k, n)] < target) {
                swap(nums, transAddress(k, n), transAddress(i++, n));
            }
        }
    }

    public int findKthLargest(int[] nums, int k) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int pivot = random.nextInt(right - left + 1) + left;
            int newPivot = partitionAroundPivot(left, right, pivot, nums);
            if (newPivot == k - 1) {
                return nums[newPivot];
            } else if (newPivot > k - 1) {
                right = newPivot - 1;
            } else { 
                left = newPivot + 1;
            }
        }
        return nums[k - 1];
    }

    public int transAddress(int i, int n) {
        return (2 * n - 2 * i - 1) % (n | 1);
    }

    public int partitionAroundPivot(int left, int right, int pivot, int[] nums) {
        int pivotValue = nums[pivot];
        int newPivot = left;
        swap(nums, pivot, right);
        for (int i = left; i < right; ++i) {
            if (nums[i] > pivotValue) {
                swap(nums, i, newPivot++);
            }
        }
        swap(nums, right, newPivot);
        return newPivot;
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
相关推荐
陈平安Java and C1 小时前
MyBatisPlus
java
秋野酱1 小时前
如何在 Spring Boot 中实现自定义属性
java·数据库·spring boot
Bunny02122 小时前
SpringMVC笔记
java·redis·笔记
feng_blog66882 小时前
【docker-1】快速入门docker
java·docker·eureka
枫叶落雨2224 小时前
04JavaWeb——Maven-SpringBootWeb入门
java·maven
m0_748232394 小时前
SpringMVC新版本踩坑[已解决]
java
码农小灰4 小时前
Spring MVC中HandlerInterceptor和Filter的区别
java·spring·mvc
乔木剑衣5 小时前
Java集合学习:HashMap的原理
java·学习·哈希算法·集合
专职5 小时前
spring boot中实现手动分页
java·spring boot·后端
神探阿航6 小时前
第十五届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组
java·算法·蓝桥杯