资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Rotate Array

chanthuang / 2569人阅读

Problem

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Solution
public class Solution {
    /**
     * @param nums: an array
     * @param k: an integer
     * @return: rotate the array to the right by k steps
     */
    public int[] rotate(int[] nums, int k) {
        // Write your code here
        k = k % nums.length; //point 1
        revert(nums, 0, nums.length-k-1); //point 2
        revert(nums, nums.length-k, nums.length-1);
        revert(nums, 0, nums.length-1);
        return nums;
        
    }
    private void revert(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71630.html

相关文章

  • [LintCode/LeetCode] Rotate Image

    摘要:两种方法,转置镜像法和公式法。首先看转置镜像法原矩阵为转置后水平镜像翻转后所以,基本的思路是两次遍历,第一次转置,第二次水平镜像翻转变换列坐标。公式法是应用了一个翻转的公式如此翻转四次即可。二者均可,并无分别。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...

    BenCHou 评论0 收藏0
  • [LintCode/LeetCode] Rotate List

    摘要:而后吾当依除取余之法,化大为小,则指针不致于越界也。后欲寻右起第结点,令快指针先行数日,及至两指针相距为,便吟鞭东指,与慢指针策马共进。快慢指针亦止于其所焉。舞动长剑,中宫直入,直取首级,而一掌劈空,已鸿飞冥冥。自此,一代天骄,霸业已成。 Problem Given a list, rotate the list to the right by k places, where k is...

    Blackjun 评论0 收藏0
  • [LintCode/LeetCode] Sliding Window Maximum/Median

    摘要:窗口前进,删队首元素保证队列降序加入当前元素下标从开始,每一次循环都将队首元素加入结果数组 Sliding Window Maximum Problem Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration fro...

    crelaber 评论0 收藏0
  • [LintCode/LeetCode] Merge Sorted Array

    Problem Given two sorted integer arrays A and B, merge B into A as one sorted array. Notice You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements ...

    summerpxy 评论0 收藏0
  • [LintCode/LeetCode] Remove Duplicates from Sorted

    摘要:思路原数组长度为,则返回原数组长度不为,则至少有个元素。将所有不重复的数值赋给,而当和相等时,不做处理。最后返回的就是不同元素的个数,也是新数组的长度。只有在时,才对赋值。注意,每次初始化的时候要分两种情况,这就意味着从的时候开始遍历。 Remove Duplicates from Sorted Array I Problem Given a sorted array, remove ...

    WalkerXu 评论0 收藏0

发表评论

0条评论

chanthuang

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<