首页 > 代码库 > leetcode_1_Two Sum
leetcode_1_Two Sum
描述:
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
思路:
思路很简单,将所有的元素放入HashSet中,如果target-Numbers[i]在hashSet中,且Numbers[i]不等于target-Numbers[i]中,满足条件,将Numbers[i]和target-Numbers[i]的index放在数组里返回即可。
代码:
public int[] twoSum(int[] numbers, int target) { int []result=new int[2]; HashSet<Integer>hp=new HashSet<Integer>(); int i=0,len=numbers.length-1; for(int num:numbers) hp.add(num); boolean flag=false; while(i<len) { flag=hp.contains(target-numbers[i]); if(flag) { result[0]=i+1; for(int j=i;j<=len;j++) if(target-numbers[i]==numbers[j]) result[1]=j+1; if(result[0]==result[1]) { flag=false; i++; continue; } else break; } i++; } return result; }
结果:
leetcode_1_Two Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。