Leetcode (2) array element right shift

Source: Internet
Author: User

Description: The number of array elements is n, the right shift K-bit, such as 12345, 3-bit right shift after 34512

Answer the idea: 12345 full rotation to get 54321

Rotate the top 3 bits 34521

Rotate the rear two bits 34512

Processing core is rotating reverse (vector<int> &nums,int begin,int end)

The rotation separator is k=k%n (k is the number of moving bits, n is the array length).

Class Solution {
Public
void reverse (vector<int>& num,int Begin,int end) {
int t=begin+ (end-begin)/2;
int tmp=0;
int i=0;
while (begin<=t) {
tmp=num.at (begin);
num.at (BEGIN) =num.at (end-i);
num.at (end-i) =tmp;
begin++;
i++;
}
}
void rotate (vector<int>& nums, int k) {
int n=nums.size ();
k=k%n;
if (n==2 && k==1) {
int tmp=0;
tmp=nums.at (0);
nums.at (0) =nums.at (1);
nums.at (1) =tmp;

}else if (k==n | | k==0) {

}else if (k<n) {
Reverse (nums,0,n-1);
Reverse (nums,0,k-1);
Reverse (nums,k,n-1);
}
}
};

Leetcode (2) array element right shift

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.