leetcode 31. 下一个排列 【时间击败 100%】 【内存击败 92.17%】

2023-05-06,,

对于该题,我本来兴致勃勃地想到了两个优化,但从提交结果来看根本看不出来有什么区别,但我发4我说的都是真的 -3-

 1  public void nextPermutation(int[] nums) {
2 if (nums.length <= 1) return;
3
4 for (int s = nums.length - 1; s >= 0; s--) {
5 if (s == 0) {
6 //把这个for循环放到大循环里,重复利用寄存器已缓存数据,原理类似数组分块优化
7 for (int j = 0, k = nums.length - 1; j < k; j++, k--) swap(nums,j,k);
8 return;
9 }
10 if (nums[s - 1] < nums[s]) {
11 int v = Integer.MAX_VALUE, index = -1;
12 for (int j = nums.length - 1; j >= s; j--) {
13 if (nums[s - 1] < nums[j] && nums[j] < v) {
14 v = nums[j];
15 index = j;
16 }
17 }
18
19 swap(nums,s-1,index);
20 for (int j = s, k = nums.length - 1; j < k; j++, k--) swap(nums,j,k);
21 return;
22 }
23 }
24 }
25 //final在Java里有内联优化的作用,不会产生额外的函数调用消耗
26 final void swap(int[]a,int i,int j){
27 int t=a[i];
28 a[i]=a[j];
29 a[j]=t;
30 }

leetcode 31. 下一个排列 【时间击败 100%】 【内存击败 92.17%】的相关教程结束。

《leetcode 31. 下一个排列 【时间击败 100%】 【内存击败 92.17%】.doc》

下载本文的Word格式文档,以方便收藏与打印。