Two Sum Solutions in Java
Number 1
Difficulty Easy
Acceptance 45.6%
Link LeetCode
Solutions
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/two-sum/description//// Author : liuyubobobo/// Time : 2017-11-15import java.util.HashMap;/// Brute Force/// Time Complexity: O(n^2)/// Space Complexity: O(1)public class Solution1 {public int[] twoSum(int[] nums, int target) {for(int i = 0 ; i < nums.length; i ++)for(int j = 0 ; j < nums.length ; j ++)if(nums[i] + nums[j] == target){int[] res = {i, j};return res;}throw new IllegalStateException("the input has no solution");}private static void printArr(int[] nums){for(int num: nums)System.out.print(num + " ");System.out.println();}public static void main(String[] args) {int[] nums = {0, 4, 3, 0};int target = 0;printArr((new Solution1()).twoSum(nums, target));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/two-sum/description//// Author : liuyubobobo/// Time : 2017-11-15/// Updated: 2018-12-28import java.util.HashMap;/// Two-Pass Hash Table/// Time Complexity: O(n)/// Space Complexity: O(n)public class Solution2 {public int[] twoSum(int[] nums, int target) {HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();for(int i = 0 ; i < nums.length ; i ++)record.put(nums[i], i);for(int i = 0 ; i < nums.length; i ++){Integer index = record.get(target - nums[i]);if(index != null && index != i){int[] res = {i, index};return res;}}throw new IllegalStateException("the input has no solution");}private static void printArr(int[] nums){for(int num: nums)System.out.print(num + " ");System.out.println();}public static void main(String[] args) {int[] nums = {0, 4, 3, 0};int target = 0;printArr((new Solution2()).twoSum(nums, target));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/two-sum/description//// Author : liuyubobobo/// Time : 2017-11-15import java.util.HashMap;/// One-Pass Hash Table/// Time Complexity: O(n)/// Space Complexity: O(n)public class Solution3 {public int[] twoSum(int[] nums, int target) {HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();for(int i = 0 ; i < nums.length; i ++){int complement = target - nums[i];if(record.containsKey(complement)){int[] res = {i, record.get(complement)};return res;}record.put(nums[i], i);}throw new IllegalStateException("the input has no solution");}private static void printArr(int[] nums){for(int num: nums)System.out.print(num + " ");System.out.println();}public static void main(String[] args) {int[] nums = {0, 4, 3, 0};int target = 0;printArr((new Solution3()).twoSum(nums, target));}}