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

    Given a rotated sorted array, recover it to sorted array in-place.
    
    Example
    [4, 5, 1, 2, 3] -> [1, 2, 3, 4, 5]
    
    Challenge
    In-place, O(1) extra space and O(n) time.
    
    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]

    我的做法是先扫描不是ascending order的两个点,然后reverse array三次,分别是(0, i), (i+1, num.length-1), (0, num.length-1)

     1 public class Solution {
     2     /**
     3      * @param nums: The rotated sorted array
     4      * @return: The recovered sorted array
     5      */
     6     public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
     7         // write your code
     8         if (nums==null || nums.size()==0 || nums.size()==1) return;
     9         int i = 0;
    10         for (i=0; i<nums.size()-1; i++) {
    11             if (nums.get(i) > nums.get(i+1)) break;
    12         }
    13         if (i == nums.size()-1) return;
    14         reverse(nums, 0, i);
    15         reverse(nums, i+1, nums.size()-1);
    16         reverse(nums, 0, nums.size()-1);
    17     }
    18     
    19     public void reverse(ArrayList<Integer> nums, int l, int r) {
    20         while (l < r) {
    21             int temp = nums.get(l);
    22             nums.set(l, nums.get(r));
    23             nums.set(r, temp);
    24             l++;
    25             r--;
    26         }
    27     }
    28 }
  • 相关阅读:
    如何把git上的小程序项目跑起来
    异常好用的六种vue组件通信方式
    2021.8.10面试总结
    高频面试题总结
    21年8.6面试总结
    2021.8.4上海微创软件(主react)电话面试
    promis封装各种请求
    各个框架解决跨域问题
    华人运通(主vue)前端研发初级工程师
    css常用命名
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4386181.html
Copyright © 2011-2022 走看看