Leetcode LeetCode algorithm check-in learning day 2

3. Rotate the array

Given an array, move the elements in the array k positions to the right, where k is a non-negative number.
Insert picture description here
Method 1: own stupid way

class Solution {
    
    
    public void rotate(int[] nums, int k) {
    
    
        if(k>=0){
    
    
            int length = nums.length;
            k = k%length;
            int num=0;
            int[] nums1 = new int[length];
            for(int i=0;i<length-k;i++){
    
    
                nums1[i+k]=nums[i];
            }
            for(int j=length-k;j<length;j++){
    
    
                nums1[num]=nums[j];
                num++;
         }
            for(int m=0;m<length;m++){
    
    
               nums[m] = nums1[m];
          }
      }
        
    }
}

Method two: self-improved method

class Solution {
    
    
    public void rotate(int[] nums, int k) {
    
    
        if(k>=0){
    
    
            int length=nums.length;
            k = k%length;
            int[] temp = new int[length];
            for(int i=0;i<length;i++){
    
    
                temp[(i+k)%length] = nums[i];
            }
            for(int i=0;i<length;i++){
    
    
                nums[i] = temp[i];
            }
        }

    }
}

Third, the official method 1-use additional arrays (similar to my method two)

class Solution {
    
    
    public void rotate(int[] nums, int k) {
    
    
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; ++i) {
    
    
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/rotate-array/solution/xuan-zhuan-shu-zu-by-leetcode-solution-nipk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Method 4: Official Method 2-Array Flip
The space complexity of this method is O(1)
Insert picture description here

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 += 1;
            end -= 1;
        }
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/rotate-array/solution/xuan-zhuan-shu-zu-by-leetcode-solution-nipk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/Shadownow/article/details/112696184