给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
package com.twosum.demo;
/**
* @Author: mann
* @Date: 2018/10/28 0:08
*/
import java.util.HashMap;
import java.util.Map;
/**
* 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
* <p>
* 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
* <p>
* 示例:
* <p>
* 给定 nums = [2, 7, 11, 15], target = 9
* <p>
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
*/
public class twoSum {
public static void main(String[] args) {
// 运行
int[] nums = {2, 7, 11, 15};
int target = 9;
// 暴力破解
twoSumViolence(nums, target);
// 两次Hash
twoSumTwoHash(nums,target);
// 一次Hash
twoSumOneHash(nums,target);
}
/**
* 暴力破解
*
* @param nums
* @param target
*/
public static void twoSumViolence(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
System.out.println("暴力解题思路,时间复杂度f(n^2):[" + i + "," + j + "]");
}
}
}
}
/**
* 两次hash表
* @param nums
* @param target
*/
public static void twoSumTwoHash(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 key = target - nums[i];
if (map.containsKey(key) && map.get(key) != i) {
int [] a = new int [] {i,map.get(key)};
System.out.println("两次Hash表,时间复杂度为f(n):[" + a[0]+ "," + a[1]+"]");
}
}
}
/**
* 一次Hash
* @param nums
* @param target
*/
public static void twoSumOneHash(int[] nums,int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i =0 ; i < nums.length; i ++) {
int key = target -nums[i];
if (map.containsKey(key)) {
int [] a = new int[] {map.get(key),i};
System.out.println("一次Hash表,时间复杂度为f(1):[" + a[0]+ "," + a[1]+"]");
}
// 此步骤很重要,否则无法添加map值
map.put(nums[i],i);
}
}
}
评论