• LeetCode Array Easy 189. Rotate Array


    ---恢复内容开始---

    Description

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

    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]

    Note:

    • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
    • Could you do it in-place with O(1) extra space?

    问题描述:给定一个长度为n的数组和一个非负整数k,向右旋转k部。

    思路,首先这里k是可以大于数组的长度的。我采用最暴力的解法,这种解法效率很低,提交之后只能到13%-85% 效率不固定

    public void Rotate(int[] nums, int k) {
            k = k % nums.Length;
            int[] temp = new int[k];
            if(k== nums.Length)
                return;
            int length = nums.Length;
            for(int i = 0; i < k; i++)
                temp[i] = nums[length - k + i];
            for(int i = length - k -1; i >=0; i--)
                nums[i+k]=nums[i];
            for(int i = 0; i < k; i++)
                nums[i]=temp[i];
        }

    解法二  采用反转的方式,先把所有的数组反转,然后反转前k个元素,再反转后n-k个元素

    public class Solution {
        public void Rotate(int[] nums, int k) {
            k = k % nums.Length;
            Reverse(nums, 0, nums.Length-1);
            Reverse(nums, 0, k-1);
            Reverse(nums, k, nums.Length-1);
        }
        private void Reverse(int[] arr, int start, int end){
            while(start < end){
                int temp = arr[start];
                arr[start]=arr[end];
                arr[end]=temp;
                start++;
                end--;
            }
        }
    }

     但是 实测发现,后一种方法效率还不如第一种方法。

  • 相关阅读:
    C++中static修饰的静态成员函数、静态数据成员
    C++友元函数、友元类
    C++异常处理
    运行时类型识别RTTI
    AD转换
    敏捷模式下的测试用例该如何存在?
    使用Postman轻松实现接口数据关联
    接口测试Mock利器-moco runner
    python测开平台使用dockerfile构建镜像
    MySQL – 用SHOW STATUS 查看MySQL服务器状态
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9582960.html
Copyright © 2020-2023  润新知