LeetCode 189. Rotate Array (旋轉數組)

來源:互聯網
上載者:User

標籤:reverse   www   數字   with   targe   --   利用   his   例子   

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

 

題目標籤:Array

  題目給了我們一個數組 和 k。 讓我們 旋轉數組 k 次。

  這裡有一個很巧妙的方法:

    利用數組的length - k 把數組 分為兩半;

    reverse 左邊和右邊的數組;

    reverse 總數組。

 

  舉一個例子: 

  1 2 3 4 5 6 7  如果k = 3 的話, 會變成 5 6 7 1 2 3 4

  1 2 3 4 5 6 7  middle = 7 - 3 = 4,分為左邊 4個數字,右邊 3個數字

  4 3 2 1 7 6 5  分別把左右reverse 一下

  5 6 7 1 2 3 4  把總數組reverse 一下就會得到答案

 

 

Java Solution:

Runtime beats 15.37% 

完成日期:04/13/2017

關鍵詞:Array

關鍵點:利用k把數組分兩半;reverse左右兩邊數組;reverse總數組

 

 1 public class Solution  2 { 3     public void rotate(int[] nums, int k)  4     { 5         if(nums == null || nums.length == 0 || k % nums.length == 0) 6             return; 7          8         int turns = k % nums.length; 9         int middle = nums.length - turns;10         11         reverse(nums, 0, middle-1); // reverse left part12         reverse(nums, middle, nums.length-1); // reverse right part13         reverse(nums, 0, nums.length-1); // reverse whole part 14     }15     16     public void reverse(int[] arr, int s, int e)17     {18         while(s < e)19         {20             int temp = arr[s];21             arr[s] = arr[e];22             arr[e] = temp;23             24             s++;25             e--;26         }27     }28 }

參考資料:

http://www.cnblogs.com/grandyang/p/4298711.html

 

LeetCode 演算法題目列表 - LeetCode Algorithms Questions List

 

LeetCode 189. Rotate Array (旋轉數組)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.