Leet Code OJ 189. Rotate Array [Difficulty: Easy]
題目: 
 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. 
 Hint: 
 Could you do it in-place with O(1) extra space?
翻譯: 
 旋轉一個n個元素的數組右移k步。 
 例如,n是7,k是3,數組是 [1,2,3,4,5,6,7],旋轉后變成 [5,6,7,1,2,3,4]。 
 提示:嘗試盡可能的使用多種方案,這里至少有3種不同的方式來解決這個問題。 
 你可以在原數組上完成操作,并且使用O(1)的額外空間嗎?
分析: 
 首先要理解題目所謂的旋轉。[1,2,3,4,5,6,7]旋轉右移1步,將變成[7,1,2,3,4,5,6]。由于移動元素的過程中,會發生覆蓋,以下方案使用了一個臨時數組來備份原數組,再進行移動。O(1)的空間復雜度的方案,筆者暫時沒想出來,歡迎大家留言交流下自己的實現方案。
代碼:
public class Solution {public void rotate(int[] nums, int k) {if(k>nums.length){k=k%nums.length;}int[] nums2=new int[nums.length];for(int i=0;i<nums.length;i++){nums2[i]=nums[i];}for(int i=0;i<nums.length;i++){int m=i-k;if(m<0){m+=nums.length;}nums[i]=nums2[m];}} }總結
以上是生活随笔為你收集整理的Leet Code OJ 189. Rotate Array [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Leet Code OJ 328. Od
 - 下一篇: Leet Code OJ 172. Fa