Leetcode-Rotate Array(189 ,61)

Rotate Array(189 ,61)

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]

Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

Show Tags

Show Similar Problems

三步:全部反轉(zhuǎn);反轉(zhuǎn)序列1 ;反轉(zhuǎn)序列2

public class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
    
    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }

}

Rotate List(61)

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Subscribe to see which companies asked this question.

Since n may be a large number compared to the length of list. So we need to know the length of linked list.After that, move the list after the (l-n%l )th node to the front to finish the rotation.

Ex: {1,2,3} k=2 Move the list after the 1st node to the front

Ex: {1,2,3} k=5, In this case Move the list after (3-5%3=1)st node to the front.

So the code has three parts.

  1. Get the length
  2. Move to the (l-n%l)th node

3)Do the rotation

public ListNode rotateRight(ListNode head, int n) {
    if (head==null||head.next==null) return head;
    ListNode dummy=new ListNode(0);
    dummy.next=head;
    ListNode fast=dummy,slow=dummy;

    int i;
    for (i=0;fast.next!=null;i++)//Get the total length 
        fast=fast.next;
    
    for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
        slow=slow.next;
    
    fast.next=dummy.next; //Do the rotation
    dummy.next=slow.next;
    slow.next=null;
    
    return dummy.next;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評(píng)論 0 33
  • 晚安,歡迎來到泡面閱讀,我是呵呵我的天。 在高二和同學(xué)一起吃壽司認(rèn)識(shí)的的你,你是那么的愛笑,不用一個(gè)星期,我們就成...
    呵呵我的天閱讀 365評(píng)論 0 0
  • 轉(zhuǎn)眼擇擇小朋友已上大班,明年就將邁入小學(xué)的校園。他從初入園的“小乖乖”變成了非常享受幼兒園生活的“老油條”,...
    張牙舞爪的小蟹女閱讀 299評(píng)論 0 0
  • 我們跟到了荷蘭機(jī)場。海關(guān)每個(gè)人都拿著槍戒備森嚴(yán)。l沒多久就在保鏢的護(hù)送下走了過來。 一個(gè)上大的大講堂里,我們飛速跑...
    綠嶼柚安閱讀 228評(píng)論 0 0

友情鏈接更多精彩內(nèi)容