首页 > 代码库 > Leetcode001 two sum
Leetcode001 two sum
/* c++ STL is much nore than what i think before in these aspects: * initializer for node element in struct node; * compare function in struct : overload operation * index not iterator used in this function. */class Solution {public: struct node{ int value; int order; node(int v,int index):value(v), order(index){} }; struct { bool operator()(node a, node b){ return a.value<=b.value; } }compare; vector<int> twoSum(vector<int>& nums, int target) { vector<int>re; vector<node>sor; for(int i=0;i<nums.size();i++)sor.push_back(node(nums[i],i)); sort(sor.begin(),sor.end(),compare); for(int tmp,i=0,j=sor.size()-1;i<j;) { tmp=sor[i].value+sor[j].value; if(tmp== target) { re.push_back(sor[i].order); re.push_back(sor[j].order); break; } else if(tmp < target)i++; else j--; } return re; } };
look the solution in java from explantation on leetcode
/* so beautiful and clean* hashmap..........*/public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution");}
Leetcode001 two sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。