LeetCode-203:Remove Linked List Elements

来源:互联网 发布:yum nothing to do 编辑:程序博客网 时间:2024/05/22 18:56

原题描述如下:

Rotate an array of n elements to the right byk 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.

题意给定一个数字和一个数字,该数字代表该数组倒数第k个数的索引值,将以该数字分成的两部分前后倒置。

解题思路:分别将两个部分反转,再将整个数组反转。

Java代码:

public class Solution {
    public void rotate(int[] nums, int k) {
        
        int length = nums.length;
        k = k % length;
        
        for(int i=0; i<(length-k)/2; ++i){
            int temp = nums[i];
            nums[i] = nums[length-k-i-1];
            nums[length-k-i-1] = temp;
        }
        
        for(int i=length-k; i<length-k/2; ++i){
            int temp = nums[i];
            nums[i] = nums[2*length-i-k-1];
            nums[2*length-i-k-1] = temp;
        }
        
        for(int i=0; i<length/2; ++i){
            int temp = nums[i];
            nums[i] = nums[length-i-1];
            nums[length-i-1] = temp;
        }
    }
}
0 0
原创粉丝点击