leetcode 两数之和 java
2018-10-01 13:30
323 查看
给定一个整数数组和一个
目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Solution { public static int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for(int i = 0;i<nums.length;i++){ int complement = target - nums[i]; if(map.containsKey(complement)){ return new int[] {map.get(complement),i}; } map.put(nums[i],i); } throw new IllegalArgumentException("no two sum solution"); } public static void main(String[] args) { int [] a = new int[]{2,7,11,15}; int [] b = twoSum(a,9); System.out.println(Arrays.toString(b)); } }[/code] 阅读更多
相关文章推荐
- leetcode-2-两数相加(add two numbers)-java
- leetcode算法题:两数相加(Java实现-效率超过100%提交者)
- LeetCode 29. 两数相除(java)
- [Leetcode] 2. 两数相加 java
- 【LeetCode-面试算法经典-Java实现】【165-Compare Version Numbers(比较版本号)】
- 57. Insert Interval-leetcode-java
- 【leetcode】113. Path Sum II【java】
- 【leetcode】114. Flatten Binary Tree to Linked List【java】
- [Leetcode] 404. 左叶子之和 java
- Jump Game leetcode java
- LeetCode 16 3Sum Closest(C,C++,Java,Python)
- 【leetcode】69. Sqrt(x)【java】
- [leetcode]31.Next Permutation(Java实现)
- leetcode 240 Search a 2D Matrix II java 算法
- jiler的LeetCode学习笔记 java版本Two Sum
- leetcode 第20题<Valid Parentheses>(java)
- leetcode-java-122. Best Time to Buy and Sell Stock II
- [leetcode-330]Patching Array(java)
- 【LeetCode】401 Binary Watch (java实现)
- Leetcode:38. Count and Say(JAVA)