From : www.LeetCode.com
Description
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.
Example
Given nums = [2, 7, 11, 15], target = 9Because nums[0] + nums[1] = 2 + 7 = 9return [0, 1]
中文介绍
描述
给定一个int型数组,和一个目标数。
例如:int nums = {2,7,11,15},target = 9
要求:
求出int数组中,哪两个数之和等于目标数。将这两个数的下标存到一个int数组中,返回该数组。
如上例,2和7之和等于9,因此返回2和7的下标,即0,1。
解决方案
使用双重for循环遍历数组,如果找到合适的值,则返回。若找不到,返回数组[0,0]
代码实现(JAVA)
class Solution {
public int[] twoSum(int[] nums, int target) {
int sum = 0;
for(int i=0;i<nums.length-1;i++){
for(int k=i+1;k<nums.length;k++){
sum = nums[i] +nums[k];
if(sum == target){
int [] arr = new int [2];
arr[0] = i;
arr[1] = k;
return arr;
}
}
}
return new int []{0,0};
}
}