leetcode Two Sum 解决思路

来源:互联网 发布:org.apache.struts2 编辑:程序博客网 时间:2024/06/11 07:18
/* * 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 jif (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]+"  ");}}}}

原创粉丝点击