题目来源
题目描述
题目解析
这道题和leetcode:849. 到最近的人的最大距离几乎一模一样,而本题是要求求索引
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <map>
#include <random>
#include <ctime>
#include <iterator>
using namespace std;
class Solution{
// 至少有一个人,至少有一个位置
int maxDistToClosestIdx(std::vector<int> &seat){
int N = seat.size();
std::vector<int> left(N, N), right(N, N);
// 往左边看,看左边里它最近的距离
for (int i = 0; i < N; ++i) {
if(seat[i] == 1){ // 如果当前位置已经有人
left[i] = 0; // 那么距离为0
}else if(i > 0){
left[i] = left[i - 1] + 1 ;
}else{
left[i] = N;
}
}
for (int i = N - 1; i >= 0; --i) {
if(seat[i] == 1){
right[i] = 0;
}else if(i == N - 1){
right[i] = N ;
}else{
right[i] = right[i + 1] + 1;
}
}
// 如果有多个这样的座位,则坐到索引最小的那个座位
int maxDis = 0, idx = -1;
int cnt = 0;
for (int i = N - 1; i >= 0; --i) {
if(seat[i] == 0){ // [当前位置没有人坐时]
int dis = std::min(left[i], right[i]); // 要做到距离最远的位置 = 里它最近的距离是:看左边的距离和右边的距离比较小的那个
if(dis >= maxDis){
maxDis = dis;
idx = i;
}
}else{
cnt++;
}
}
return cnt == 0 ? 0 : cnt == N ? -1 : idx;
}
std::vector<int> splitInt(std::string str, char ch){
int j = 0;
std::vector<int> ans;
str += ch;
for (int i = 0; i < str.size(); ++i) {
if(str[i] == ch){
ans.push_back(stoi(str.substr(j, i - j)));
j = i + 1;
}
}
return ans;
}
public:
// 0 1 2 3 4 5 6 7 8 9
// 1 1 1
int lastSeat(int N, std::string str){
int ans = -1;
std::vector<int> seat(N, 0);
str = str.substr(1, str.size() - 2);
auto vec = splitInt(str, ',');
for(auto i : vec){
if(i == 1){
int idx = maxDistToClosestIdx(seat);
if(idx != -1){
seat[idx] = 1;
}
ans = idx;
}else{
seat[std::abs(i)] = 0;
}
}
return ans;
}
};
int main(){
int N = 0;
std::string str;
// std::cin >> N;
// std::cin >> str;
N = 10;
str = "[1,1,1,1,-4,1]";
Solution a;
std::cout << a.lastSeat(N, str);
}