当前位置:   article > 正文

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

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

题目:

题解:

  1. class Solution {
  2. Random random = new Random();
  3. public void wiggleSort(int[] nums) {
  4. int n = nums.length;
  5. int x = (n + 1) / 2;
  6. int mid = x - 1;
  7. int target = findKthLargest(nums, n - mid);
  8. for (int k = 0, i = 0, j = n - 1; k <= j; k++) {
  9. if (nums[transAddress(k, n)] > target) {
  10. while (j > k && nums[transAddress(j, n)] > target) {
  11. j--;
  12. }
  13. swap(nums, transAddress(k, n), transAddress(j--, n));
  14. }
  15. if (nums[transAddress(k, n)] < target) {
  16. swap(nums, transAddress(k, n), transAddress(i++, n));
  17. }
  18. }
  19. }
  20. public int findKthLargest(int[] nums, int k) {
  21. int left = 0, right = nums.length - 1;
  22. while (left <= right) {
  23. int pivot = random.nextInt(right - left + 1) + left;
  24. int newPivot = partitionAroundPivot(left, right, pivot, nums);
  25. if (newPivot == k - 1) {
  26. return nums[newPivot];
  27. } else if (newPivot > k - 1) {
  28. right = newPivot - 1;
  29. } else {
  30. left = newPivot + 1;
  31. }
  32. }
  33. return nums[k - 1];
  34. }
  35. public int transAddress(int i, int n) {
  36. return (2 * n - 2 * i - 1) % (n | 1);
  37. }
  38. public int partitionAroundPivot(int left, int right, int pivot, int[] nums) {
  39. int pivotValue = nums[pivot];
  40. int newPivot = left;
  41. swap(nums, pivot, right);
  42. for (int i = left; i < right; ++i) {
  43. if (nums[i] > pivotValue) {
  44. swap(nums, i, newPivot++);
  45. }
  46. }
  47. swap(nums, right, newPivot);
  48. return newPivot;
  49. }
  50. public void swap(int[] a, int i, int j) {
  51. int temp = a[i];
  52. a[i] = a[j];
  53. a[j] = temp;
  54. }
  55. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/942610
推荐阅读
相关标签
  

闽ICP备14008679号