leetcode题解-31. Next Permutation
来源:互联网 发布:淘宝里的一元秒杀在哪 编辑:程序博客网 时间:2024/05/16 16:19
题目:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).The replacement must be in-place, do not allocate extra memory.Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3 → 1,3,23,2,1 → 1,2,31,1,5 → 1,5,1
看到这个题读了很多遍都读不懂,然后就去看答案了==大概的题意就是假设数组是降序排列,然后现在有一个地方出现了反转,例如这样:[5,3,1,9,7,4,2]
在1和9的位置出现异常,我们需要做的就是找到该位置,然后将之后的数组变成升序排列。可以分为下面三个步骤:
- 找到反转点
- 从尾部向前找到后半区比该值(1)大的数,交换两个数
- 将后面的数组排序成升序
代码入下:
public void nextPermutation(int[] nums) { /* 1. Reverse find first number which breaks descending order. */ int i=nums.length-1; for(; i>=1; i--) if(nums[i-1]<nums[i]) break; /* if no break found in step 1 */ if(i==0){ /* for case "1" and "1111" */ if(nums.length==1 || nums[0]==nums[1]) return; /* for case "54321" */ int lo=i, hi=nums.length-1; while(lo<hi) swap(nums, lo++, hi--); return; } /* 2. Exchange this number with the least number that's greater than this number. */ /* 2.1 Find the least number that's greater using binary search, O(log(nums.length-i)) */ int j = binarySearchLeastGreater(nums, i, nums.length-1, nums[i-1]); /* 2.2 Exchange the numbers */ if(j!=-1) swap(nums, i-1, j); /* 3. Reverse sort the numbers after the exchanged number. */ int lo=i, hi=nums.length-1; while(lo<hi) swap(nums, lo++, hi--); } public int binarySearchLeastGreater(int[] nums, int lo, int hi, int key){ while(lo<=hi){ int mid = lo + (hi-lo)/2; if(nums[mid]>key){ lo = mid+1; } else { hi = mid-1; } } return hi; } public void swap(int[] nums, int i, int j){ int tmp = nums[j]; nums[j] = nums[i]; nums[i] = tmp; }
0 0
- leetcode题解-31. Next Permutation
- leetcode题解-31. Next Permutation
- Leetcode题解-31. Next Permutation
- LeetCode题解:Next Permutation
- LeetCode题解:Next Permutation
- leetcode 题解 || Next Permutation 问题
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- Unity3D实验,关于碰撞消息的机制
- 2016年编程题总结(一):
- Solr 搭建搜索服务器
- 单例模式
- NoSQL简介
- leetcode题解-31. Next Permutation
- pandas操作
- Windows10资源管理器占用CPU过高解决办法
- Codeforces 4D Mysterious Present
- (转)java正则表达式相关知识
- python xml
- 最短路(1)--dijkstra
- [AHOI2006] BZOJ1266 上学路线route-图论-最短路树-最小割
- 最长上升子序列(动态规划)