给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
示例:
给定 nums = [8, 7, 21, 15], target = 23
因为 nums[0] + nums[3] = 8 + 15= 23
所以返回 [0, 3]
解答:
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[j]==target-nums[i]){
return new int[] {i,j};
}
}
}
throw new IllegalArgumentException("没有符合条件项");
}