Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题意:在数组中找出两个数,使得之和为target。给出这两个数在数组中的坐标,注意坐标下标开始为1.
题目地址:https://oj.leetcode.com/problems/two-sum/
解题思路:使用map,将所有的数存放其中,然后遍历数组,在map中找另外一个数与当前数相加等于目标值。
public int[] twoSum(int[] numbers, int target) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<numbers.length;i++) map.put(numbers[i], i); boolean b =false; int j=0; int n=0; for(j=0;j<numbers.length;j++) { int a = target-numbers[j]; b = map.containsKey(a); if(b) { n=map.get(a); //判断不为当前数的下标 if(n!=j) break; } } if(b) { if(n>j) { int a[] = {j+1,n+1}; return a; }else { int a[] = {n+1,j+1}; return a; } }else { return null; } }
相关推荐
Leetcode two sum java 解法
def twoSum(nums, target): hash_map = {} for i, num in enumerate(nums): complement = target - num if complement in hash_map: return [hash_map[complement], i] hash_map[num] = i return [] ``` ###...
答案LeetCode_1_TwoSum LeetCode 问题:给定一个整数数组,找出两个数字,使它们相加为特定的目标数字。 函数 twoSum 应该返回两个数字的索引,使它们相加为目标,其中 index1 必须小于 index2。 请注意,您返回的...
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2)...
c c语言_leetcode 0001_two_sum
c++ C++_leetcode题解之001. Two Sum.cpp
Leetcode 1 two sum C++ code
"两数之和"(TwoSum)是LeetCode上的一道经典题目,也是许多初学者和面试者必练的问题。本资料包"python-leetcode面试题解之两数之和TwoSum.zip"显然包含了关于这个问题的Python解决方案。 **问题描述:** 给定一个...
leetcode 2sum # Programming-Problems This will have many problems from all over the web, As of writing this readme there is Haskell 99: 28 finished + Huffman Coding LeetCode: LC1: 2Sum [Easy] LC2: Add...
c语言入门 c语言_leetcode题解01-two-sum.c
java入门 java_leetcode题解之001_Two_Sum
TwoSum 如何贡献: 收录题库 LeetCode (还有4题未录入, 分别为 LRU Cache, Copy List with Random Pointer, Populating Next Right Pointers in Each Node I && II) PIE (未录入) CC150 (未录入) EPI (未录入) 每一个...
leetcode 答案 Leetcode Leetcode test 11 Container With Most Water 这里题目的分析图如下: 所以我们需要找的是ai,aj中的最小值作为高,然后找(i-j)的最大值作为长 ...twoSum ThreeSum FourSum...KSum
js js_leetcode题解之1-two-sum.js
Two-Sum leetcode两数之和代码 题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组...
def twoSum(nums, target): hash_map = {} for i, num in enumerate(nums): complement = target - num if complement in hash_map: return [hash_map[complement], i] hash_map[num] = i return [] ``` 这...
python python_leetcode题解之170_Two_Sum_III-Data_structure_design.py
这个方法实现的程序通过了LeetCode检测,提示用了16个测试,用时492ms,超过了75%的人
python python_leetcode题解之167_Two_Sum_II_Input_array_is_sorted.py
第一题的四种方法,包括暴力破解和字典、列表。我也是刚开始练习