LeedCode-Two Sum
1. 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.
public class Solution { public int[] TwoSum(int[] nums, int target) { int[] sumnumbers =new int[2]; for (int i = 0; i <= nums.Length-1; i++) { for (int j = 0; j <= nums.Length-1; j++) { if (nums[i] + nums[j] - target == 0 && i != j) { if (i < j) { sumnumbers[0] = i; sumnumbers[1] = j; return sumnumbers; } else { sumnumbers[0] =j; sumnumbers[1] = i; return sumnumbers; } } } } return sumnumbers; } }
Top sulution 【O(n)】 C++的top解决方案
vector<int> twoSum(vector<int> &numbers, int target) { //Key is the number and value is its index in the vector. unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < numbers.size(); i++) { int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them if (hash.find(numberToFind) != hash.end()) { //+1 because indices are NOT zero based result.push_back(hash[numberToFind] + 1); result.push_back(i + 1); return result; } //number was not found. Put it in the map. hash[numbers[i]] = i; } return result; }
C#的仿写
public class Solution { public int[] TwoSum(int[] nums, int target) { int[] RetIndecis = {0,0}; Hashtable hsNums = new Hashtable(); hsNums.Clear(); //i is the latter index for(int i=0;i<nums.Length;i++) { int targetKey = target - nums[i]; //if targetKey exist if(hsNums.ContainsKey(targetKey)) { RetIndecis[1] = i + 1; RetIndecis[0] = (int)hsNums[targetKey]; return RetIndecis; } //key is the number and value is the index,filter the number which has existed if(!hsNums.ContainsKey(nums[i])) hsNums.Add(nums[i],i + 1); } return(RetIndecis); } }
如果您觉得本文对你有用,不妨帮忙点个赞,或者在评论里给我一句赞美,小小成就都是今后继续为大家编写优质文章的动力,carson拜谢! 欢迎您持续关注我的博客:)
作者:carsonche
出处:https://home.cnblogs.com/u/carsonche/
版权所有,欢迎保留原文链接进行转载:)