剑指offer62 圆圈中最后剩下的数字
0, 1, …, n-1这n个数字(n>0)排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。
求出这个圆圈里剩下的最后一个数字。
样例
输入:n=5 , m=3
输出:3
思路1:
创建一个vector nums 保存0-n-1数值,模拟环形链表,然后循环依次删除第m位置上的数值。时间复杂度为O(mn),空间复杂度为O(n);
AcWing-82 C++ code:
class Solution {
public:
int lastRemaining(int n, int m){
if(n < 1 || m < 1){
return -1;
}
vector<int> nums;
for(int i = 0; i < n; i++){
nums.push_back(i);
}
int currentIndex = 0;
int nextIndex = 0;
while(n > 1){
int time = 1;
while(time < m){
time++;
currentIndex++;
if(currentIndex >= nums.size()){
currentIndex = 0;
}
}
nums.erase(nums.begin() + currentIndex);
if(currentIndex >= nums.size()){
currentIndex = 0;
}
n--;
}
return nums[0];
}
};
思路2:
balabala…emmm,时间复杂度为O(n),空间复杂度为O(1)。
AcWing-82 C++ code:
class Solution {
public:
int lastRemaining(int n, int m){
if(n < 1 || m < 1){
return -1;
}
int last = 0;
for(int i = 2; i <= n; i++){
last = (last + m) % i;
}
return last;
}
};