当前位置:网站首页>[189. rotation array]

[189. rotation array]

2022-06-11 02:36:00 Cat star people who love Durian


One 、 Subject requirements

Give you an array , Rotate the elements in the array to the right k A place , among k It is a non negative number .
Example 1:
Input : nums = [1,2,3,4,5,6,7], k = 3
Output : [5,6,7,1,2,3,4]
explain :
Rotate right 1 Step : [7,1,2,3,4,5,6]
Rotate right 2 Step : [6,7,1,2,3,4,5]
Rotate right 3 Step : [5,6,7,1,2,3,4]
Example 2:
Input :nums = [-1,-100,3,99], k = 2
Output :[3,99,-1,-100]
explain :
Rotate right 1 Step : [99,-1,-100,3]
Rotate right 2 Step : [3,99,-1,-100]
Tips :
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105

source : Power button (LeetCode)
link :https://leetcode.cn/problems/rotate-array

Two 、 Thought analysis

Ideas :
 Insert picture description here

void reverse(int* nums,int left,int right)
{
    
    while(left < right)
    {
    
        int tmp= nums[left];
        nums[left]=nums[right];
        nums[right]=tmp;
        left++;
        right--;

    }
}
void rotate(int* nums, int numsSize, int k){
    
     if(k >= numsSize)
        k %= numsSize;
     reverse(nums,0,numsSize-k-1);
     reverse(nums,numsSize-k,numsSize-1);
     reverse(nums,0,numsSize-1);
}

The above is the whole content of this article , If there are mistakes in the article or something you don't understand , Communicate more with meow bloggers . Learn from each other and make progress . If this article helps you , Can give meow bloggers a concern , Your support is my biggest motivation .

原网站

版权声明
本文为[Cat star people who love Durian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110143215560.html