Last active
April 21, 2016 01:53
-
-
Save cangoal/38fa3a14f7f7489a2669b10576f72940 to your computer and use it in GitHub Desktop.
LintCode - Previous Permutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ArrayList<Integer> previousPermuation(ArrayList<Integer> nums) { | |
// write your code | |
if(nums == null || nums.size() < 2) return nums; | |
int start = -1; | |
// find the fisrt "large" number | |
for(int i=nums.size()-2; i>=0; i--){ | |
if(nums.get(i) > nums.get(i+1)){ | |
start = i; | |
break; | |
} | |
} | |
// if this "large" number exists, find the first smaller number | |
if(start != -1){ | |
int index = nums.size() - 1; | |
while(index > start){ | |
if(nums.get(index) < nums.get(start)){ | |
swap(nums, index, start); | |
break; | |
} | |
index--; | |
} | |
} | |
// reverse the scanned part in the first round | |
int left = start + 1, right = nums.size()-1; | |
while(left < right){ | |
swap(nums, left++, right--); | |
} | |
return nums; | |
} | |
private void swap(ArrayList<Integer> nums, int i, int j){ | |
int temp = nums.get(i); | |
nums.set(i, nums.get(j)); | |
nums.set(j, temp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment