LeetCode Two Sum
2014-11-23 00:31
351 查看
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 { public int[] twoSum(int[] numbers, int target) { int[] sorted = numbers.clone(); Arrays.sort(sorted); int l = 0, r = numbers.length - 1; int sum = 0; while (l < r) { sum = sorted[l] + sorted[r]; if (sum == target) { int i=0,j=0; for (int k = 0; k < numbers.length; k++) { if (numbers[k]==sorted[l]&& i==0) i=k+1; if (numbers[k]==sorted[r]) j=k+1; } return new int[]{Math.min(i,j),Math.max(i,j)}; } if (sum > target) { r--; continue; } if (sum < target) { l++; continue; } } return null; } }
相关文章推荐
- LeetCode Two Sum 两数之和
- 【LeetCode】(C#)1. Two Sum(Easy)
- LeetCode(001) Two Sum (Java)
- Sum—LeetCode-167 Two Sum II Input array is sorted
- leetcode解题笔记:Two sum系列解题思路
- leetcode之twosum
- leetcode twosum
- LeetCode—Two Sum
- Leetcode--Two Sum
- Two Sum | LeetCode(1)
- LeetCode Two Sum
- 【leetcode】Two Sum(unordered_map的使用)
- LeetCode Sum of Two Integers
- leetcode167: Two Sum II - Input array is sorted
- LeetCode 1: Two Sum
- Leetcode:Two Sum
- LeetCode Two Sum、3Sum、3Sum Closest、4Sum
- LeetCode167—Two Sum II - Input array is sorted
- LeetCode:Two Sum II - Input array is sorted
- leetcode Sum of Two Integers