LeetCode 189 Rotate Array

LeetCode189 Rotate Array

問題來源LeetCode189 Rotate Array

問題描述

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.

Related problem: Reverse Words in a String II

問題分析

這道題就是對數組以某個節點進行反轉,有一種思路是先反轉數組,然後在分別反轉某節點的前後兩部分數組。

代碼實現

public void rotate(int[] nums, int k) {
    if(nums==null||nums.length<1||k==0||k>=nums.length) return;
    k %= nums.length;//k值超過數組長度時
    reverse(nums,  0, nums.length-1);//翻轉整個數組
    reverse(nums, 0, k-1);//翻轉前k個數
    reverse(nums, k, nums.length-1);//翻轉剩下的數
}
void reverse(int[] nums,int i,int j){
    while (i < j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
        i++;
        j--;
    }
}

參考https://www.cnblogs.com/grandyang/p/4298711.html

大神的帖子裏面介紹了更多的方法,大家可以去看一下。這裏我就不重複的複製粘貼了。

LeetCode學習筆記持續更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章