LeetCode 1 - Two Sum
编程技术  /  houtizong 发布于 3年前   148
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> map; vector<int> res(2,-1); for(int i=0; i<nums.size(); i++) { int diff = target - nums[i]; if(map.count(diff)) { res[0] = map[diff]+1; res[1] = i+1; break; } else { map[nums[i]] = i; } } return res;}
Java代码如下:
public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<nums.length; i++) { int key = target - nums[i]; Integer val = map.get(key); if(val != null) { res[0] = val+1; res[1] = i+1; break; } else { map.put(nums[i], i); } } return res;}// if you just return the values, not the indices, you can also do thispublic int[] twoSum0(int[] nums, int target) { Arrays.sort(nums); int[] res = new int[2]; int start = 0, end = nums.length-1; while(start < end) { int sum = nums[start] + nums[end]; if(sum < target) { end--; } else if(sum > target) { start++; } else { res[0] = nums[start]; res[1] = nums[end]; return res; } } return res;}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接