Two Sum
2014-08-12 19:02
232 查看
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
代码:
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
代码:
public class Solution_1 { public static int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; for(int i = 0; i < numbers.length; i++) for(int j = i + 1; j < numbers.length; j++) if(numbers[i] + numbers[j] == target) { result[0] = i + 1; result[1] = j + 1; } return result; } public static void main(String[] args) { // TODO Auto-generated method stub int[] numbers = {2,7,11,15}; int[] result = twoSum(numbers, 9); System.out.println(result[0] + " " + result[1]); } }
相关文章推荐
- LeetCode 1. Two Sum
- leetcode 1. Two Sum
- [Leetcode] 1. Two Sum
- [Easy]Two Sum
- LeetCode-Two Sum
- leetcode: 1 Two Sum
- 【leetcode】Two Sum
- [leetcode, python] Two Sum 两数之和等于某数
- leetcode(1)Two Sum
- LeetCode #1 Two Sum
- LeetCode-E-Two Sum
- Sum—LeetCode-1 Two Sum
- [LeetCode]Two Sum
- 1. Two Sum
- LeetCode 1.Two Sum
- Leetcode习题记录——Two Sum
- leetcode学习 1.two sum
- 《LeetCode》:Two Sum
- Leetcode-1:Two Sum
- LeetCode题解(Golang实现)--Two Sum