【Code】cpp不定时更新

1. Jewels and Stones

  • String的大小和访问string中的第i个char: s.size()    ;    s[i] .   其中s为string
  • sort函数的用法:
    • 必须声明头文件#include <algorithm>
    • 三个input,第一个是排序的第一个元素的地址,第二个是排序的第二个的地址,第三个是排序方法 -- 通过bool的一个函数确定是从大到小还是从小到大。sort函数每次会把两个数值放进这个bool函数进去比大小。
    • bool函数中写成const能避免不小心改动了a和b的值。 &在这里表引用。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool cmp(const int &a, const int &b){
	return a<b;
}

int main()
{
	vector<int> myvec{1,2,7,6,1,7};
	sort(myvec.begin(), myvec.end(), cmp);
	cout << "The order is:" << endl;
	for (int item:myvec)
		cout << item << ' ';
	cout << endl;

	return 0;
}
  • Lambda 表达式   -- C++11的新功能
sort(myvec2.begin(), myvec2.end(), [](int a, int b) -> bool { return a < b; });
myvec.push_back(3);  myvec.pop_back();

2. To lower Case

3. Big Countries

4. Unique Morse Code Words

  • set用于存储不同的transformations.

5. Hamming Distance

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<int> v(32);
    for(vector<int>::iterator i = v.begin();i!= v.end();++i)
    {
        cout << *i << " ";
    }
    cout << endl;
    return 0 ;
 }

6. Flipping an Image

7. Judge Route Circle

8. Projection Area of 3D Shapes

  • vector赋值
vector< vector<int> > grid(2, vector<int>(2));
int b[2][2]={{1,2},{3,4}};
for(int i=0; i<2;i++){
	for(int j=0;j<2;j++){
   		grid[i][j] = b[i][j];
   	}
}

9. Merge Two Binary Trees

  • TreeNode *newNode = new TreeNode(t1->val + t2->val);

10. Self Dividing Numbers

  • 关键在于求余后判断是否余数能整除

11. Array Partition 1

扫描二维码关注公众号,回复: 3998906 查看本文章
  • 要使min的和最大就要按从小到大的顺序排列后两两作为一对,取前一个数字。(否则如果不这样取,就会导致大数被浪费)
  • 第一个解法,直接sort完隔一个数取值相加
  • 第二个解法把数值映射到一个reference table中,记录每个数出现的次数;然后从小到大通过flag来决定是要加还是不管。

12. Middle of the Linked List

  • 关键在于设置两个指针同时跑,p2每次跑两格,p1每次跑一格,所以当p2跑完的时候p1就刚好在一半的位置。

13. Transpose Matrix

  • 建一个新的向量矩阵,然后把A中的值一一拷贝到B内

14. Leaf-Similar Trees

  • 关键在于写一个函数来收集全部的叶子 - 递归的方法,终止条件是左右指针都指向nullptr,然后每次都先找左边后找右边
  • nullptr vs null:  null是旧的已经被弃用的,它会被当作一个int;而nullptr是新的,它还是会被当成一个pointer。
  • 树节点和一个vector被当作input放进函数里面的时候的表达方式如下,此时调用函数的时候直接输入树根和vector的名字就好,在函数里面也一样。
void leaves(TreeNode* root, vector<int>& leaf)

15. Number Complement

16. Uncommon Words

class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        istringstream wrdA(A);
        istringstream wrdB(B);
        vector<string> output;
        unordered_map<string, int> words;
        string word;
        while(wrdA>>word){
            words[word]++;
        }
        while(wrdB>>word){
            words[word]++;
        }
        for(auto iter = words.begin(); iter!=words.end();iter++){
            if(iter->second==1){
                output.push_back(iter->first);
            }
        }
        return output;
    }
};

17. Reverse Words in a String |||

  • istringstream读入每一个数,然后用reverse(tmp.begin(), tmp.end())实现反转,再重新存入一个string类型的result

猜你喜欢

转载自blog.csdn.net/u013541048/article/details/81612848