zoukankan      html  css  js  c++  java
  • Recover Rotated Sorted Array

    三步反转法

    Recover Rotated Sorted Array 
    
     
    Given a rotated sorted array, recover it to sorted array in-place.
    
    Have you met this question in a real interview? Yes
    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] Challenge In-place, O(1) extra space and O(n) time. Tags Sorted Array Array Related Problems Medium Sort Colors 36 % Easy Rotate String
    public class Solution {
        /**
         * @param nums: The rotated sorted array
         * @return: The recovered sorted array
         */
        private void reverse(ArrayList<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);
            }
        }
    
        public void recoverRotatedSortedArray(ArrayList<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);
                    return;
                }
            }
        }
    }
    

      

  • 相关阅读:
    Lua build and install
    tomcat 配置的另外一种方法
    debian vsftp
    git(1)
    jd-gui安装
    debian crash log查看
    ros学习笔记
    51nod 1138 连续整数的和(数学公式)
    51nod 1428 活动安排问题(优先队列)
    Codeforces Round #347 (Div. 2) (练习)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7263434.html
Copyright © 2011-2022 走看看