2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_1.java 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2020-08-09 20:39 . optimize solutions
package com.hit.basmath.learn.hash_table;
import java.util.HashMap;
import java.util.Map;
/**
* 1. Two Sum
* <p>
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* <p>
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
* <p>
* Example:
* <p>
* Given nums = [2, 7, 11, 15], target = 9,
* <p>
* Because nums[0] + nums[1] = 2 + 7 = 9,
* <p>
* return [0, 1].
*/
public class _1 {
/**
* Solution 1: Violence method
*
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
/**
* Solution 2: Two pass hash table
*
* @param nums
* @param target
* @return
*/
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> aMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
aMap.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (aMap.containsKey(complement) &&
aMap.get(complement) != i) {
return new int[]{i, aMap.get(complement)};
}
}
return null;
}
/**
* Solution 3: One pass hash table
*
* @param nums
* @param target
* @return
*/
public int[] twoSum3(int[] nums, int target) {
Map<Integer, Integer> aMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (aMap.containsKey(complement)) {
return new int[]{aMap.get(complement), i};
}
aMap.put(nums[i], i);
}
return null;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助