题解 | #NC110 旋转数组#

旋转数组

http://www.nowcoder.com/practice/e19927a8fd5d477794dac67096862042

反转三次数组即可完成循环移动的结果。
第一次反转整个数组;
第二次从数组开始反转需要移动的次数个;
第三次反转剩下的部分。

import java.util.*;


public class Solution {
    /**
     * 旋转数组
     * @param n int整型 数组长度
     * @param m int整型 右移距离
     * @param a int整型一维数组 给定数组
     * @return int整型一维数组
     */
    public int[] solve (int n, int m, int[] a) {
        // write code here
        int k = m % a.length;
        reverse(a,0,a.length-1);
        reverse(a,0,k-1);
        reverse(a,k,a.length-1);
        return a;
    }

    public static void reverse(int[] arr,int start, int end){
        int temp = 0;
        while(start < end){
            temp = arr[end];
            arr[end] = arr[start];
            arr[start] = temp;
            end--;
            start++;
        }
    }
}
全部评论

相关推荐

04-01 16:02
已编辑
武汉工程大学 Java
牛客98843461...:处女面??我还种马面渣男面处男面呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务