LeetCode第235场周赛题解
截断句子
按照题目要求模拟即可,把单词读入到vector中,然后按要求拼接即可
class Solution {
public:
string truncateSentence(string s, int k) {
vector<string> a;
stringstream str(s);
string t;
while(str >> t) a.push_back(t);
string ans = "";
for (int i = 0; i < k; i++) {
ans = ans + a[i] + " ";
}
ans.pop_back();
return ans;
}
};
查找用户活跃分钟数
大致思路:
- 按照ID标号由小到大排序,相同ID的按照时间大小由小到大排序
- 按照ID标号切分数组,统计相同ID编号的数组中用户活跃分钟数
class Solution {
public:
static bool cmp(vector<int>& a, vector<int>& b) {
if (a[0] == b[0]) return a[1] < b[1];
return a[0] < b[0];
}
vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) {
vector<int> ans(k);
//先按照编号排序
sort(logs.begin(), logs.end(), cmp);
int n = logs.size(), i = 0;
int cnt = 0;
while(i < n) {
int j = i;
vector<int> tmp = logs[i];
while(j < n && tmp[0] == logs[j][0]) j++;
j--;
unordered_map<int,bool> count;
int cnt = 0;
for (;i <= j; i++) {
// cout << logs[i][0] << " " << logs[i][1] << endl;
if (count[logs[i][1]]) continue;
count[logs[i][1]] = true;;
cnt++;
}
// cout << cnt << endl;
if (cnt != 0) ans[cnt - 1]++;
}
return ans;
}
};
绝对差值和
大致思路:
- 找出差值和最大的数的位置
pos
- 遍历
nums1
数组,找出和nums2[pos]
差值的绝对和最小的数的位置min_pos
nums1[pos] = nums1[min_pos]
class Solution {
public:
int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
const int MOD = 1e9 + 7;
int sum = 0, n = nums1.size();
int pos, maxx = 0; //找到绝对值之差最大的位置
for (int i = 0; i < n; i++) {
int sub = abs(nums1[i] - nums2[i]);
sum = (sum + sub) % MOD;
if (sub >= maxx) {
maxx = sub;
pos = i;
}
}
if (sum == 0) return 0;
int min_pos;
for (int i = 0; i < n; i++) {
if (i == pos) continue;
int sub = abs(nums1[i] - nums2[pos]);
if (sub <= maxx) {
maxx = sub;
min_pos = i;
}
}
nums1[pos] = nums1[min_pos];
sum = 0;
for (int i = 0; i < n; i++) {
int sub = abs(nums1[i] - nums2[i]);
sum = (sum + sub) % MOD;
}
return sum;
}
};