新手算法学习之路----Recover_Rotated_Sorted_Array

题目:

Given a rotated sorted array, recover it to sorted array in-place.

Clarification

What is rotated array?

  • For example, the orginal array is [1,2,3,4], The rotated array of it can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]
Example

[4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5],or[1,1,1,1,1,1,1,-1,1,1,1,1,1,1,1,1,1] -> [-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

 

代码:

public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
        // write your code
        int start =0, end = nums.size()-1,mid,min_location;
        //先找到,数组里面最小的数,然后以这个数来进行转换
        int min_nums=0;
        for(int i=1;i<end;i++){
            if(nums.get(0)>nums.get(i)){
               min_nums = i;
               break;
            }
        }
        //三部转换法
        ChangeLocation(nums, 0, min_nums-1);
        ChangeLocation(nums, min_nums, nums.size()-1);
        ChangeLocation(nums, 0, nums.size()-1);
    }
   public void ChangeLocation(ArrayList<Integer> a, int l, int h){
        int temp;
        for(int low=l, high=h; low< high; low++, high--){
            temp = a.get(low);
            a.set(low, a.get(high));
            a.set(high, temp);
            }
    }

下面这一种应用到二分法,但是对[1,1,1,1,1,1,1,-1,1,1,1,1,1,1,1,1,1] 情况不成立,只对数组是排序且没重复有效

 public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
        // write your code
      int start =0, end = nums.size()-1,mid,min_location;
        while (start+1<end){
            mid = start+(end -start)/2;
            if(nums.get(mid)<=nums.get(end)){
                end= mid;
            }else if(nums.get(mid)>nums.get(end)){
                start = mid;
            }
        }
        if(nums.get(start)>nums.get(end)) min_location = end;
        else if(nums.get(start)<nums.get(end)) min_location = start;
        else return;
        
        //三部转换法
        ChangeLocation(nums, 0, min_location-1);
        ChangeLocation(nums, min_location, nums.size()-1);
        ChangeLocation(nums, 0, nums.size()-1);
        //System.out.println(nums);
    }
   public void ChangeLocation(ArrayList<Integer> a, int l, int h){
        int temp;
        for(int low=l, high=h; low< high; low++, high--){
            temp = a.get(low);
            a.set(low, a.get(high));
            a.set(high, temp);
            }
    }

 

posted @ 2017-07-11 10:01  JunLiu37  阅读(172)  评论(0编辑  收藏  举报