zoukankan      html  css  js  c++  java
  • *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]
     1 /**
     2  * 本代码由九章算法编辑提供。没有版权欢迎转发。
     3  * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
     4  * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
     5  * - 更多详情请见官方网站:http://www.jiuzhang.com/
     6  */
     7 
     8 import java.util.ArrayList;
     9 
    10 
    11 public class Solution {
    12     /**
    13      * @param nums: The rotated sorted array
    14      * @return: The recovered sorted array
    15      */
    16     private void reverse(ArrayList<Integer> nums, int start, int end) {
    17         for (int i = start, j = end; i < j; i++, j--) {
    18             int temp = nums.get(i);
    19             nums.set(i, nums.get(j));
    20             nums.set(j, temp);
    21         }
    22     }
    23 
    24     public void recoverRotatedSortedArray(ArrayList<Integer> nums) {
    25         for (int index = 0; index < nums.size() - 1; index++) {
    26             if (nums.get(index) > nums.get(index + 1)) {
    27                 reverse(nums, 0, index);
    28                 reverse(nums, index + 1, nums.size() - 1);
    29                 reverse(nums, 0, nums.size() - 1);
    30                 return;
    31             }
    32         }
    33     }
    34 }
  • 相关阅读:
    JavaScript 开发的45个经典技巧
    LINQ
    迭代器
    【工具篇】抓包中的王牌工具—Fiddler (1-环境搭建)
    浏览器本地数据库 IndexedDB 基础详解
    Python爬虫实践 -- 记录我的第二只爬虫
    美团App用户界面分析
    APP测试要点—UI、功能测试
    Emmagee--APP性能测试工具的基本使用
    APP测试工具与技术
  • 原文地址:https://www.cnblogs.com/hygeia/p/4837033.html
Copyright © 2011-2022 走看看