500. 键盘行(权重思维,给每一个字母打上权重标记)

将26位英文字母按照键盘行的特点来标记。
则 ABCDEFGHIJKLMHOPQRSTUVWXYZ
对应 12210111011122000010020202
然后使用字符-a的形式来判断字符所在的行。

  1. class Solution {
  2. public:
  3. vector<string> findWords(vector<string>& words) {
  4. vector<string> ans;
  5. string rowIdx = "12210111011122000010020202";
  6. for (auto & word : words) {
  7. bool isValid = true;
  8. char idx = rowIdx[tolower(word[0]) - 'a'];
  9. for (int i = 1; i < word.size(); ++i) {
  10. if(rowIdx[tolower(word[i]) - 'a'] != idx) {
  11. isValid = false;
  12. break;
  13. }
  14. }
  15. if (isValid) {
  16. ans.emplace_back(word);
  17. }
  18. }
  19. return ans;
  20. }
  21. };

268. 丢失的数字

这一题的线性时间常数空间解法太秀了,应用到了之前只出现一次的位运算方法,非常巧妙。

  1. class Solution {
  2. public:
  3. int missingNumber(vector<int>& nums) {
  4. int res = 0;
  5. int n = nums.size();
  6. for (int i = 0; i < n; i++) {
  7. res ^= nums[i];
  8. }
  9. for (int i = 0; i <= n; i++) {
  10. res ^= i;
  11. }
  12. return res;
  13. }
  14. };

zj-future03. 快递中转站选址

这一题的核心思想就是,一个一维数组里面有1也有0,求一个位置距离所有1的和最短。这个位置就是所有1的位置的中位数!!!
这题是二维的情况,因此求x轴和y轴的中位数即可

  1. class Solution {
  2. public:
  3. int buildTransferStation(vector<vector<int>>& area) {
  4. vector<int> x,y;
  5. int n=area.size(),m=area[0].size(),i,j;
  6. for(i=0;i<n;i++)for(j=0;j<m;j++)if(area[i][j])
  7. {
  8. x.push_back(i);
  9. y.push_back(j);
  10. }
  11. sort(x.begin(),x.end());
  12. sort(y.begin(),y.end());
  13. int l=x.size(),u=x[l>>1],v=y[l>>1],ans=0;
  14. for(i=0;i<l;i++)ans+=abs(x[i]-u)+abs(y[i]-v);
  15. return ans;
  16. }
  17. };