LeetCode Two Sum
来源:互联网 发布:淘宝秒杀软件是真的吗 编辑:程序博客网 时间:2024/05/13 08:59
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小的最大值可能会找不到,所以会出错,只要找到比target小的最大值即可求得结果。
import java.sql.Struct;import java.util.Arrays;import java.util.Comparator;public class Solution {class Point{public int x;public int y;};class IndexComparator implements Comparator<Object>{public final int compare(Object pfirst,Object psecond) {Point point1 = (Point)pfirst;Point point2 = (Point)psecond;int diff = point1.x - point2.x;if(diff>0)return 1;if(diff<0)return -1;else return 0;}}public int[] twoSum(int[] nums, int target) { int [] index = new int[2]; int i=0; int j=nums.length-1; Point[]points = new Point[nums.length]; for (int k = 0; k < points.length; k++) { points[k] = new Point(); if(target<0) points[k].x = -nums[k]; else {points[k].x = nums[k];}points[k].y = k;} if(target<0)target = - target; Arrays.sort(points, new Solution.IndexComparator()); while(i<=j){ while(points[j].x>target)j--; if(points[i].x+points[j].x>target){ j--; } else{ if(points[i].x+points[j].x<target){ i++; } else {break;} } } index[0]=Math.min(points[i].y, points[j].y)+1; index[1]=Math.max(points[i].y, points[j].y)+1; return index; } public static void main(String [] args){ Solution solution = new Solution(); int [] numbers = new int[5]; numbers[0]=-1;numbers[1]=2; numbers[2]=1;numbers[3]=-4; numbers[4]=-5; int [] index = solution.twoSum(numbers, 0); System.out.println(index[0]+" "+index[1]); }}
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 期待为线性时间的选择算法
- C++数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。(牛客剑指offer)
- Game Center 的 Leaderboard 中提交浮点数据(float)
- 1285确定比赛名次
- java并发(4)-synchronized
- LeetCode Two Sum
- 解决dos打开界面变小和打开软件字体乱码的问题
- SharedPreferences的使用
- taskAffinity属性
- android中跨进程通讯的4种方式
- golang internals
- Visual display of quantitative information
- MFC单文档视图拆分窗口
- java的单例、static修饰符及static的继承