LeetCode-两数之和
求两数之和:给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
解法1:
package leetcode;
import java.util.Arrays;
public class leetcode1{
int[] a1 = new int[2];
public int[] twoSum(int[] nums, int target) {
for(int i=0;i <=nums.length-1;i++){
for(int j=1;j<=nums.length-1;j++){
//System.out.println(nums[i]);
//System.out.println(nums[j]);
if (nums[i]+nums[j] == target) {
System.out.println("ok");
a1[0] = i;
a1[1] = j;
}
}
}
return a1;
}
public static void main(String[] args) {
leetcode1 leetcode1= new leetcode1();
int [] s1 = {2, 7, 11, 15};
leetcode1.twoSum(s1,9);
System.out.println(leetcode1.a1[0]);
System.out.println(leetcode1.a1[1]);
}
}
解法2 hashmap
package leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class leetcode1{
int[] a1 = new int[2];
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
a1[0] = i;
a1[1] = complement;
}
}
return a1;
}
public static void main(String[] args) {
leetcode1 leetcode1= new leetcode1();
int [] s1 = {2, 7, 11, 15};
System.out.println(leetcode1.twoSum(s1,9)[0]);
System.out.println(leetcode1.twoSum(s1,9)[1]);
}
}