LeetCode------Two Sum
2018-01-26 17:02
417 查看
1. Description: Given an array of integers, return indices of the two numbers such that they add up to a specified target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
2. 翻译:给定一个整数数组和一个目标值,返回数组中两个元素的下标,并使这两个元素之和等于该目标值。可以假设每个目标值对应的两个下标值的解是唯一的,并且数组中的同一个元素不能够使用两次。
比如说数组nums = [2,7,11,15],目标值target = 9, 因为2 + 7 = 9,所以返回[0,1]。
3.思路:这道题目比较简单,属于easy难度。我们可以直接通过两层for循环进行遍历的方式,依次检查两个元素之和是否等于目标值,一旦发现符合条件的两个数组元素,立即返回这两个下标值所组成的数组,如果遍历结束后仍没有发现这样的两个元素,则返回null,代码如下。Submit Solution结果为Accepted。
4.代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
//首先数组长度必须大于等于两个元素
if(nums.length>1){
for(int i = 0; i<nums.length; i++){
for(int j = i+1; j<nums.length; j++){
if((nums[i]+nums[j]) == target){
return new int[]{i,j};
}
else{
//do nothing
}
}
}
}
return null;
}
}
You may assume that each input would have exactly one solution, and you may not use the same element twice.
2. 翻译:给定一个整数数组和一个目标值,返回数组中两个元素的下标,并使这两个元素之和等于该目标值。可以假设每个目标值对应的两个下标值的解是唯一的,并且数组中的同一个元素不能够使用两次。
比如说数组nums = [2,7,11,15],目标值target = 9, 因为2 + 7 = 9,所以返回[0,1]。
3.思路:这道题目比较简单,属于easy难度。我们可以直接通过两层for循环进行遍历的方式,依次检查两个元素之和是否等于目标值,一旦发现符合条件的两个数组元素,立即返回这两个下标值所组成的数组,如果遍历结束后仍没有发现这样的两个元素,则返回null,代码如下。Submit Solution结果为Accepted。
4.代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
//首先数组长度必须大于等于两个元素
if(nums.length>1){
for(int i = 0; i<nums.length; i++){
for(int j = i+1; j<nums.length; j++){
if((nums[i]+nums[j]) == target){
return new int[]{i,j};
}
else{
//do nothing
}
}
}
}
return null;
}
}
相关文章推荐
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- Leetcode习题:1. Two Sum
- [Leetcode]Two Sum
- 个人记录-LeetCode 1.Two Sum
- *LeetCode-Two Sum
- leetcode 46: Two Sum
- [Leetcode1_Two Sum]
- 【LeetCode】Two Sum
- 【LeetCode】001.Two Sum
- leetcode-1. Two Sum
- Two Sum (LeetCode)
- [Leetcode] Two Sum
- leetcode-two sum
- leetcode 1-Two Sum
- [Leetcode]1. Two Sum
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- leetcode -Two Sum
- jiler的LeetCode学习笔记 java版本Two Sum
- [LeetCode][JavaScript]Two Sum
- Leetcode: Two Sum