- 500. 键盘行(权重思维,给每一个字母打上权重标记)">500. 键盘行(权重思维,给每一个字母打上权重标记)
- 268. 丢失的数字">268. 丢失的数字
- zj-future03. 快递中转站选址
500. 键盘行(权重思维,给每一个字母打上权重标记)
将26位英文字母按照键盘行的特点来标记。
则 ABCDEFGHIJKLMHOPQRSTUVWXYZ
对应 12210111011122000010020202
然后使用字符-a的形式来判断字符所在的行。
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> ans;
string rowIdx = "12210111011122000010020202";
for (auto & word : words) {
bool isValid = true;
char idx = rowIdx[tolower(word[0]) - 'a'];
for (int i = 1; i < word.size(); ++i) {
if(rowIdx[tolower(word[i]) - 'a'] != idx) {
isValid = false;
break;
}
}
if (isValid) {
ans.emplace_back(word);
}
}
return ans;
}
};
268. 丢失的数字
这一题的线性时间常数空间解法太秀了,应用到了之前只出现一次的位运算方法,非常巧妙。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = 0;
int n = nums.size();
for (int i = 0; i < n; i++) {
res ^= nums[i];
}
for (int i = 0; i <= n; i++) {
res ^= i;
}
return res;
}
};
zj-future03. 快递中转站选址
这一题的核心思想就是,一个一维数组里面有1也有0,求一个位置距离所有1的和最短。这个位置就是所有1的位置的中位数!!!
这题是二维的情况,因此求x轴和y轴的中位数即可
class Solution {
public:
int buildTransferStation(vector<vector<int>>& area) {
vector<int> x,y;
int n=area.size(),m=area[0].size(),i,j;
for(i=0;i<n;i++)for(j=0;j<m;j++)if(area[i][j])
{
x.push_back(i);
y.push_back(j);
}
sort(x.begin(),x.end());
sort(y.begin(),y.end());
int l=x.size(),u=x[l>>1],v=y[l>>1],ans=0;
for(i=0;i<l;i++)ans+=abs(x[i]-u)+abs(y[i]-v);
return ans;
}
};