我的垃圾程序:
package day15;
public class leetcode_1 {
public static void main(String args[])
{
int nums[]=new int[]{2,7,11,15};
int target=9;
int result[]=new int[2];
result=twoSum(nums,target);
System.out.println(result);
//System.out.println(result[0]);
//System.out.println(result[1]);
}
public static int[] twoSum(int[] nums, int target) {
int len = nums.length;
int sum = 0;
int a[] = new int[2];
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (target == nums[i] + nums[j]) {
if(i!=j) {
a[0] = j;
a[1] = i;
}
//System.out.println(a);
}
}
}
return a;
}
}
看别人程序的反思:
好家伙我真的忘记得太厉害了 竟然忘记了java数组的几种创建方法..
int a=new int[4];
int a=new int[]{1,2,3,4};
看了一眼别人的代码,很多都是使用哈希表做的。
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static void main(String args[])
{
int nums[]=new int[]{2,7,11,15};
int target=9;
int result[]=new int[2];
result=twoSum(nums,target);
System.out.println(result);
System.out.println(result[0]);
System.out.println(result[1]);
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int len = nums.length;
int result[] = new int[2];
for (int i = 0; i <len ; i++) {
if(map.containsKey(nums[i])){
result[0] = map.get(nums[i]);
result[1] = i;
return result;
}
map.put(target-nums[i],i);
}
return result;
}
}