题目
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.
大意:
给定一个int数组,要求返回数组中两个数相加的指等于指定值的位置,假定输入只有一个答案,给定的数不能使用两次!
思路:
我的思路是首先遍历一次数组中的元素,判断该数是否大于目标指,如果大于就continue,然后从它的下一个数开始遍历,判断和值是否相等于指定值!
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int temp = 0;
int one = 0;
int two = 0;
for(int i = 0;i<nums.length;i++) {
temp = nums[i];
if (temp > target) {
continue;
}
for(int j = i+1;j<nums.length;j++) {
if (nums[j] > target) {
continue;
}
if (temp + nums[j] == target) {
one = i;
two = j;
}
}
}
return new int[]{one,two};
}
}