#include <iostream> #include <vector> using namespace std; //vector: int main(){ vector<int> raw; raw.push_back(8); raw.push_back(7); raw.push_back(6); raw.push_back(3); for(vector<int>::iterator iter = raw.begin(); iter != raw.end(); iter++){ cout << *iter << endl; |
#include <iostream> #include <map> #include <string> using namespace std; int main(){ map<string, string> hashmap; map<string, string>::iterator iter; hashmap.insert(pair<string, string>("r000", "ST1")); hashmap["r111"] = "ST2"; hashmap["r222"] = "ST3"; for(iter = hashmap.begin(); iter != hashmap.end(); ++iter){ cout << iter->first << " , " << iter->second << endl; } /* r000 , ST1 r111 , ST2 r222 , ST3 */ iter = hashmap.find("r000"); if(iter != hashmap.end()){ cout << iter->second; }else{ cout << "Not found!"; } //ST1 } |
// Two Sum #include <iostream> #include <vector> #include <map> using namespace std; class Solution{ public: vector<int> twosum(vector<int> &nums, int target){ map <int, int> hashtable; //store value and index map <int, int> :: iterator iter; //iterator for find value vector <int> ansIndex(2); //store index answer for(int i = 0; i < nums.size(); i++){ iter = hashtable.find(target - nums[i]); if(iter != hashtable.end()){ ansIndex[0] = iter->second; ansIndex[1] = i; return ansIndex; }else{ //map only can change value, not key hashtable[nums[i]] = i; } } cout << "Not found!" << endl; } }; /* step by step: i->0 == 2 hashtable.find(9 - 7 == 2) (X) #hashtable is clear hashtable[2](key) = 0(value) i->1 == 7 hashtable.find(9 - 7 == 2) (O) there is a '2' in hashtable, its value is 0! now i == 1 and iter is adress of '2' which in hashtable and iter->second is hashtable[2]'s value '0' so return index(0) and index(1) */ int main(){ vector <int> arr; //imput value arr.push_back(2); arr.push_back(7); arr.push_back(11); arr.push_back(15); int target = 9; Solution kkk; //call function and print vector <int> point = kkk.twosum(arr , target); for(vector <int> :: iterator iter2 = point.begin(); iter2 != point.end(); iter2++){ cout << "Index[ " << *iter2 << " ] " << endl; } } |
留言共 4 篇留言
前一篇:N1真的難... 後一篇:SHISHAMO(シシャ...