大佬教程收集整理的这篇文章主要介绍了lleetcode 1 two sum c++,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Problem describe:https://leetcode.com/problems/two-sum/
Given an array of Integers,return inDices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution,and you may not use the same element twice.
Given nums = [2,7,11,15],target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1]
1.bruth Algorithm
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums,int target) { 4 vector<int> res; 5 for(int i = 0;i < nums.size();i++) 6 for(int j = i + 1;j < nums.size();j++) 7 if(nums[i]+nums[j]==target) 8 { 9 res.push_BACk(i); 10 res.push_BACk(j); 11 } 12 return res; 13 14 } 15 };
2.Hashmap
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums,int target) { 4 vector<int> res; 5 unordered_map<int,int> map; 6 for(int i = 0; i < nums.size();i++) 7 { 8 map[nums[i]] = i; 9 } 10 for(int i = 0;i < nums.size();i++) 11 { 12 int left = target - nums[i]; 13 if(map.count(left) && i < map[left]) 14 { 15 res.push_BACk(i); 16 res.push_BACk(map[left]); 17 } 18 } 19 return res; 20 } 21 };
以上是大佬教程为你收集整理的lleetcode 1 two sum c++全部内容,希望文章能够帮你解决lleetcode 1 two sum c++所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。