1. 程式人生 > >【Code】cpp不定時更新

【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

  • 要使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