[LeetCode] Two Sum
2014-05-12 11:22
369 查看
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=2public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] index = new int[2];
for(int i = 0; i < numbers.length - 1; i++){
for(int j = i+1; j < numbers.length; j++){
if(numbers[i]+numbers[j] == target){
index[0] = i+1;
index[1] = j+1;
}
}
}
return index;
}
}
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=2public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] index = new int[2];
for(int i = 0; i < numbers.length - 1; i++){
for(int j = i+1; j < numbers.length; j++){
if(numbers[i]+numbers[j] == target){
index[0] = i+1;
index[1] = j+1;
}
}
}
return index;
}
}
相关文章推荐
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- 学习
- 学习
- Mathematician gucci shoes
- MB Star Astrology comprises of Star Sign
- c#大数运算
- POINTERS ON C 读书日记
- 摘抄---2005-1-1
- Epub 转 txt
- Yet Another Sudoku Solver in Python
- 软件项目版本号的命名格式
- Microsoft 认证 MB7-839最新考试题库下载
- The 3n+1 Problem(求各位高手修改)
- 动态内存分配 (转载)
- hdu 4279 Number