您的位置:首页 > 其它

39. 恢复旋转排序数组

2018-03-06 21:15 302 查看
给定一个旋转排序数组,在原地恢复其排序。

说明什么是旋转数组?比如,原始数组为[1,2,3,4], 则其旋转数组可以是[1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]
样例
[4, 5, 1, 2, 3]
 -> 
[1, 2, 3, 4, 5]

public class Solution {
/*
* @param nums: An integer array
* @return: nothing
*/
// public void recoverRotatedSortedArray(List<Integer> nums) {
//     // write your code here
//     int min = nums.get(0);
//     for(int i=1;i<nums.size();i++){
//         if(nums.get(i)<min)
//             min = nums.get(i);
//     }
//     for(int i=0;i<nums.size();){
//         if(nums.get(i)==min)
//             break;
//         else{
//             nums.add(nums.get(i));
//             nums.remove(i);
//         }
//     }
// }

public void recoverRotatedSortedArray(List<Integer> nums) {
for(int index = 0; index < nums.size() - 1; index++){
if(nums.get(index) > nums.get(index + 1)){
reverse(nums, 0, index);
reverse(nums, index+1, nums.size()-1);
reverse(nums, 0, nums.size()-1);
}
}
}

public void reverse (List<Integer> nums, int start, int end){
for(int i = start, j = end; i < j; i++, j--){
int temp = nums.get(i);
nums.set(i, nums.get(j));
nums.set(j, temp);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: