leetcode Two Sum 解决思路
2017-07-18 18:56
453 查看
/* * Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. 给出一个int数组,返回数组中两个数下标,这两个数相加等于一个给出的int数,每个数只能用一次,不能自己加自己 Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. 例如: 条件: nums = [2, 7, 11, 15], target = 9, 满足: nums[0] + nums[1] = 2 + 7 = 9, 返回 : [0, 1]. */ public class Solution { public static int[] twoSum1(int[] nums, int target) { if (nums == null) { return null; } // 返回值 int result[] = new int[2]; // 遍历 for (int i = 0; i < nums.length; i++) { // 从当前下标下一位数开始遍历 不会自己加自己 for (int j = i + 1; j < nums.length; j++) { // 如果相加等于目标 就返回当前i j if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; } } } return result; } public static int[] twoSum2(int[] nums, int target) { if (nums == null) { return null; } // 返回值 int result[] = new int[2]; // 这个map用来存放已经遍历过的数据 (不用进行双层循环) Map<Integer, Integer> gone = new HashMap<>(); // 遍历数字数组 for (int i = 0; i < nums.length; i++) { // 如果已经遍历过的数中存在一个与当前数相加等于target 则返回两位数的下标 if (gone.containsKey(target - nums[i])) { result[0] = gone.get(target - nums[i]); result[1] = i; } gone.put(nums[i], i); } return result; } public static void main(String[] args) { //测试 int ints [] ={3,2,4}; int targrt = 6; int res[] = twoSum1(ints,targrt); int res2[] = twoSum2(ints,targrt); if(res != null){ for (int i = 0; i < res.length; i++) { System.out.print("第"+(i+1)+"个下标:"+res[i]+" "); } } System.out.println(); if(res2 != null){ for (int i = 0; i < res2.length; i++) { System.out.print("第"+(i+1)+"个下标:"+res2[i]+" "); } } } }
相关文章推荐
- leetcode:Sort List 使用归并排序的解决思路
- LeetCode 之 LRU Cache解决思路
- 用java解决LeetCode(1)——Two Sum
- [leetcode53]两种思路解决的Maximun Subarray
- leetcode 之 Flatten Binary Tree to Linked List 解决思路
- leetcode之 wordBreak(1)解决思路
- leetcode 之 Two Sum 解题思路
- [LeetCode] 35. Search Insert Position 解决思路
- 两种回溯方法解决子集问题的思路 leetcode 78. Subsets
- [LeetCode] 57. Insert Interval 解决思路
- [LeetCode] 116. Populating Next Right Pointers in Each Node 解决思路
- LeetCode之 Reorder List解决思路
- leetcode -- Longest Substring Without Repeating Characters -- 简单要知道思路
- Leetcode-01 two sum
- 1---LeetCode【Two Sum】|C语言|总结
- Oracle数据库ORA-00257的相关问题及解决问题的思路
- LeetCode 思路及解答
- LeetCode (1) Two Sum
- 【C/C++】解决“不是有效的win32应用程序”思路
- LeetCode 1 Two Sum