938 二叉搜索樹的範圍和
給定二叉搜索樹的根結點 root,返回 L 和 R(含)之間的所有結點的值的和。
二叉搜索樹保證具有唯一的值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
vector<int> value;
InOrder(root,&value);
int sum=0,left=0,right=6;
bool begin=false;
for(int i=0;i<value.size();i++)
{
if(value[i]==L && begin==false){
left=i;
begin=true;
}
if(value[i]==R){
right=i;
}
}
for(int i=left;i<right+1;i++){
sum=sum+value[i];
}
return sum;
}
void InOrder(TreeNode* root,vector<int> * value){
if(root!=NULL)
{
InOrder(root->left,value);
value->push_back(root->val);
InOrder(root->right,value);
}
}
};
static const auto kSpeedUp = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
二叉搜索樹:
左節點小於根節點,右節點大於根節點
注意點:
(1)vector的作爲函數參數需要傳指針,傳值是無效的。
(2)動態數組vector訪問可以直接和數組一樣vector [1],添加元素可以使用push_back。
(3)對於指針對象的成員函數或成員變量,應該使用->而不能使用.
而對於&或者對象本身,需要使用.而不應該使用->
InOrder(root->right,value); //正確
InOrder(root.right,value); //錯誤
(4)最後一段增加代碼執行速度用的。
(5)NULL空指針,不是null
//完全迭代遍歷
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if (root==NULL){
return 0;
}
if(root->val>=L && root->val<=R)
return root->val + rangeSumBST( root->left, L, R) + rangeSumBST( root->right, L, R);
else
return rangeSumBST( root->left, L, R) + rangeSumBST( root->right, L, R);
}
};
//根據二叉搜索樹來進行迭代遍歷
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if (root==NULL){
return 0;
}
if(root->val>=L && root->val<=R)
return root->val + rangeSumBST( root->left, L, R) + rangeSumBST( root->right, L, R);
else if(root->val<L)
return rangeSumBST( root->right, L, R);
else
return rangeSumBST( root->left, L, R);
}
};
881. 救生艇
第 i 個人的體重爲 people[i],每艘船可以承載的最大重量爲 limit。
每艘船最多可同時載兩人,但條件是這些人的重量之和最多爲 limit。
返回載到每一個人所需的最小船數。(保證每個人都能被船載)。
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
int num=0;
sort(people.begin(),people.end());
for(int i=0,j=people.size()-1;j>i;j--){
if(people[j]+people[i]<=limit){
num++;
if(i+2==j){ //中間只剩下一個人
num++;
break;
}
i++;
}
else{
num++;
if(i+1==j){ //中間沒有人,但是兩個人的重量加起來也超過最大限制。
num++;
break;
}
}
}
return num;
}
};
static int speed_up = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
注意點:
(1)vector數組大小,vector[vector.size()-1]
(2)void sort(RanIt first, RanIt last, cmp);前兩個參數爲迭代器指針,分別指向容器的首尾,第三個參數爲比較方法,默認是升序排列。必須的頭文件#include < algorithm>和using namespace std; 可以自定義cmp:
bool cmp(int x, int y) {
return x > y;
}
844. 比較含退格的字符串
給定 S 和 T 兩個字符串,當它們分別被輸入到空白的文本編輯器後,判斷二者是否相等,並返回結果。 # 代表退格字符。
class Solution {
public:
bool backspaceCompare(string S, string T)
{
vector<char>v1,v2;
for(char element:S)//處理S中的所有字符,結果存儲在v1中
{
if(element!='#')
v1.push_back(element);
else
{
if(!v1.empty())
v1.pop_back();
}
}
for(char element:T)//處理T中的所有字符,結果存儲在v2中
{
if(element!='#')
v2.push_back(element);
else
{
if(!v2.empty())
v2.pop_back();
}
}
if(v1!=v2)//判斷得到的v1和v2是否相同
return false;
return true;
}
};
// 還沒想清楚爲什麼錯
// class Solution {
// public:
// bool backspaceCompare(string S, string T) {
// string s,t;
// for(int i=0;i<S.length();i++){
// if(S[i]!='#')
// {
// s=s+S[i];
// }else{
// if(s.length()!=0){
// s.pop_back();
// }
// }
// }
// for(int i=0;i<T.length();i++){
// if(T[i]!='#')
// {
// t=t+T[i];
// }else{
// if(t.length()!=0){
// t.pop_back();
// }
// }
// }
// if(s.length()!=t.length()){
// return false;
// }else{
// for(int i=0;i<s.length()-1;i++)
// {
// if(s[i]!=t[i]){
// return false;
// }
// }
// return true;
// }
// }
// };
692. 前K個高頻單詞
class Solution {
public:
typedef pair<string, int> PAIR;
struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
if(lhs.second != rhs.second)
return lhs.second > rhs.second;
else{
return lhs.first < rhs.first;
}
}
};
struct CmpByValue1 {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
return lhs.first.compare(rhs.first)>0;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> word_map;
unordered_map<string,int> result_map;
for(int i=0;i<words.size();i++){
// map<string,int>::iterator iter;
// iter = word_map.find(words[i]);
// if(iter!=word_map.end()){
word_map[words[i]]++;
// }else{
// word_map.insert(pair<string, int>(words[i], 1));
// }
}
vector<PAIR> result(word_map.begin(), word_map.end());
sort(result.begin(), result.end(), CmpByValue());
vector<string> ans; //不能使用ans(k),會用默認值填充已分配的大小
for(int i=0;i<k;i++){
ans.push_back(result[i].first);
}
return ans;
}
};
備註:
1.對map,unordered_map {key,value}對的插入並且記錄key的個數,可以採用直接數組的方式
map[key]++;如果有存在key,則會++,
如果不存在會直接創建,而不需要:
for(int i=0;i<words.size();i++){
map<string,int>::iterator iter;
iter = word_map.find(words[i]);
if(iter!=word_map.end()){
word_map[words[i]]++;
}else{
word_map.insert(pair<string, int>(words[i], 1));
}
}
直接
for(int i=0;i<words.size();i++){
word_map[words[i]]++;
}
對於map中存儲的pair<a,b> h,讀取裏面的值可以通過h.first以及h.second來進行解讀。
2.auto使用,使得程序更加易懂和簡潔
for(auto a:words){
word_map[a]++;
}
3.sort使用
要對STL的數據結構進行排序,使用sort方法,正常情況下需要重載函數,
有兩種方法:
1.重寫一個結構體:
typedef pair<string, int> PAIR;
struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
if(lhs.second != rhs.second)
return lhs.second > rhs.second;
else{
return lhs.first < rhs.first;
}
}
};
2.重新定義一個函數:
typedef pair<string,int>node;
bool cmp(const node &a,const node &b){
if(a.second!=b.second)return a.second>b.second;
else return a.first<b.first;
}
使用時,可以用:
sort(result.begin(), result.end(), CmpByValue());
sort(result.begin(), result.end(), cmp);
注意,sort只能針對線性結構的數據結構來進行,因此,如果是需要對map,或unordered_map進行排序的話,需要先轉換數據格式到如vector中去。
typedef pair<string, int> PAIR;
vector<PAIR> result(word_map.begin(), word_map.end());
函數需要用static,否則只能寫在類的外部。
定義函數的時候sort(result.begin(), result.end(), cmp);不用加括號。
定義結構體的時候需要加括號,結構體可以寫在類的內部,函數運算相對較快。
268. 缺失數字
給定一個包含 0, 1, 2, …, n 中 n 個數的序列,找出 0 … n 中沒有出現在序列中的那個數。
第一種思路,排序,對應序號的數據如果沒有對應該爲,則爲缺失的數據。
class Solution {
public:
int missingNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
int i=0;
for(auto a:nums){
if(a!=i){
break;
}
i++;
}
return i;
}
};
最簡單的方法應該是求和,然後和1到n項的數列和對比,相差的數就是缺的這個數
0,1,2,3…這些數字求和直接用求和公式會循環的程序運行時間。
accumulate(nums.begin(),nums.end(),0),STL模板函數API接口,可以
class Solution0 {
public:
int missingNumber(vector<int>& nums) {
int size_num=nums.size();
return size_num*(size_num+1)/2-accumulate(nums.begin(),nums.end(),0);
}
};
class Solution1 {
public:
int missingNumber(vector<int>& nums) {
int size_num=nums.size();
int sum_real=size_num;
int sum_prac=0;
for(int i=0;i<size_num;i++){
sum_prac+=nums[i];
}
return size_num*(size_num+1)/2-sum_prac;
}
};
class Solution2 {
public:
int missingNumber(vector<int>& nums) {
int size_num=nums.size();
int sum_real=size_num;
int sum_prac=0;
for(int i=0;i<size_num;i++){
sum_real+=i;
sum_prac+=nums[i];
}
return sum_real-sum_prac;
}
};