导言
leetcode是一个判断型的OJ,拥有大量的算法题目,最近拿来练手
题目(原题目)
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
题目中文翻译
给定一个整数数组,返回两个数的下标,使得它们加起来的特定目标数的数值。
你可以假设每个输入将有一个确切的解决方案。
例:
给定整型数组NUMS = [ 2 , 7 ,11,15 ] ,目标= 9 ,
由于NUMS [0] + NUMS [1] = 2 + 7 = 9,
返回[ 0,1 ] 。
更新日期( 2016年2月13日) :
返回格式已改为从零开始的索引。请仔细阅读上面的更新说明。
解析
由于题目说过,假设每一个输入都有一个解决方案,所以不必担心返回result为空,那么问题就来了。应该如何解决呢?
题目说返回两个数的下标,说明这两个数的下标必然不相等。
我们假设当前遍历的数字的下标为i,即将与其相加的数字下标为j,我们将数字i从0到NUMS.length-1,对于每一个NUMS[i]来说,不必考虑下标小于它的数字与其相加,因为如果i>1,那么在当前要相加数字的第一个数字下标在[0,i-1]的时候,就已经和i相加过了,而且不相等。
所以为了方便,我们采用两个下标来记录当前相加的两个数字的下标i,j。对于每一个i来说,从下标为[i+1,nums.length]之中在NUMS数组里选出一个数字,查看是否与其相加是否与目标数字相等,一旦相等便退出循环,然后将结果返回。
代码
public class Solution {
public int[] twoSum(int[] nums, int target) {
int []result = new int [2];
for(int i=0;i<nums.length-1;i++)
for(int j=i+1;j<nums.length;j++)
{
if(nums[i]+nums[j] == target)
{
result[0]=i;
result[1]=j;
break;
}
}
return result;
}
}
测试的代码
package array;
public class leetcode1 {
public int[] twoSum(int[] nums, int target) {
int []result = new int [2];
for(int i=0;i<nums.length-1;i++)
for(int j=i+1;j<nums.length;j++)
{
if(nums[i]+nums[j] == target)
{
result[0]=i;
result[1]=j;
break;
}
}
return result;
}
public static void main(String[] args) {
leetcode1 l = new leetcode1();
int[] nums = {3,2,4};
int []result = l.twoSum(nums, 6);
System.out.println(result[0]+" "+result[1]);
}
}