import java.util.Arrays;
public class App {
public static void main(String[] args) throws Exception {
Solution a = new Solution();
int nums[] = { 1, 2, 3, 4 };
a.twoSum(nums, 6);
String stringLikeArray = Arrays.toString(a.result);
System.out.println(stringLikeArray);
}
}
class Solution {
int result[] = new int[2];
public int[] twoSum(int[] nums, int target) {
int i, j;
for (i = 0; i < nums.length; i++) {
for (j = i + 1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
result[0] = i;
result[1] = j;
}
}
}
return result;
}
}
// mark一下,leetcode的第一道题目,这道题需要双循环进行遍历,则设置两个变量就好了,很久没碰过java了,所以真的挺多东西都忘了,甚至数组的new都忘了
// 数组不是显示类,但也是继承object的对象
// Arrays需要先引用才能使用
哈希表做法
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> table = new HashMap();
int[] res = new int[2];
//把数组中的数按照<key, value>存入表中
//!!<nums[i], index> = <key, value>
//用target-遍历nums的最新的那个数;
//contains方法查看是否有对应的数在hash表,有就返回key
//没有就put进去
for(int i = 0; i < nums.length; i++){
if(table.containsKey(target - nums[i])){
res[0] = table.get(target - nums[i]);
res[1] = i;
return res;
}
table.put(nums[i], i);
}
return res;
}
}