标签:cti ons ati order continue static out 出差 find
按照题目要求模拟即可,把单词读入到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;
}
};
大致思路:
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;
}
};
标签:cti ons ati order continue static out 出差 find
原文地址:https://www.cnblogs.com/gxsoar/p/14616063.html