当前位置:网站首页>Leetcode skimming ---189
Leetcode skimming ---189
2022-07-03 10:35:00 【Long time no see 0327】
subject : Give you an array , Rotate the elements in the array to the right
kA place , amongkIt is a non negative number .
Input :nums = [1,2,3,4,5,6,7], k = 3
Output :[5,6,7,1,2,3,4]
Method 1 : Use extra arrays
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
vector<int> newArr(n);
for (int i = 0; i < n; ++i) {
newArr[(i + k) % n] = nums[i];
}
nums.assign(newArr.begin(), newArr.end());
}
};Complexity analysis
Time complexity :O(n)
Spatial complexity :O(n)
Method 2 : Circular substitution
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k = k % n;
int count = gcd(k, n);
for (int start = 0; start < count; ++start) {
int current = start;
int prev = nums[start];
do {
int next = (current + k) % n;
swap(nums[next], prev);
current = next;
} while (start != current);
}
}
};Complexity analysis
Time complexity :O(n)
Spatial complexity :O(1)
Method 3 : An array of reverse
class Solution {
public:
void reverse(vector<int>& nums, int start, int end) {
while (start < end) {
swap(nums[start], nums[end]);
start += 1;
end -= 1;
}
}
void rotate(vector<int>& nums, int k) {
k %= nums.size();
reverse(nums, 0, nums.size() - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.size() - 1);
}
};Complexity analysis
Time complexity :O(n)
Spatial complexity :O(1)
边栏推荐
- CSDN, I'm coming!
- Linear regression of introduction to deep learning (pytorch)
- Leetcode刷题---278
- Leetcode刷题---44
- Policy Gradient Methods of Deep Reinforcement Learning (Part Two)
- Leetcode刷题---704
- Adaptive Propagation Graph Convolutional Network
- What did I read in order to understand the to do list
- [LZY learning notes dive into deep learning] 3.1-3.3 principle and implementation of linear regression
- [C question set] of Ⅵ
猜你喜欢

Timo background management system

A complete mall system

6、 Data definition language of MySQL (1)

High imitation bosom friend manke comic app

Data classification: support vector machine

LeetCode - 715. Range module (TreeSet)*****

Implementation of "quick start electronic" window dragging

Powshell's set location: unable to find a solution to the problem of accepting actual parameters

7、 Data definition language of MySQL (2)

Configure opencv in QT Creator
随机推荐
深度学习入门之自动求导(Pytorch)
Leetcode skimming ---283
GAOFAN Weibo app
Tensorflow—Neural Style Transfer
[C question set] of Ⅵ
Leetcode - 5 longest palindrome substring
LeetCode - 900. RLE iterator
Ind yff first week
Softmax 回归(PyTorch)
Content type ‘application/x-www-form-urlencoded; charset=UTF-8‘ not supported
High imitation wechat
ECMAScript--》 ES6语法规范 ## Day1
熵值法求权重
Codeup: word replacement
神经网络入门之模型选择(PyTorch)
Ut2016 learning notes
[LZY learning notes -dive into deep learning] math preparation 2.1-2.4
EFFICIENT PROBABILISTIC LOGIC REASONING WITH GRAPH NEURAL NETWORKS
Model evaluation and selection
Leetcode刷题---35