多语言展示
当前在线:1835今日阅读:23今日分享:25

LeetCode题目1 Two Sum

LeetCode刷题,是为了获得面经,这是题目1的java实现解法
工具/原料

笔记本,eclipse

方法/步骤
1

题目: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=9Output: index1=1, index2=2

2

方法1:采用了排序算法加上二分查找得到结果,最快需要O(nlogn)  public class Solution {    public int[] twoSum(int[] numbers, int target) { int[] arr = Arrays.copyOf(numbers, numbers.length); int[] result = new int[2]; Arrays.sort(numbers); //Arrays. int i=0; int j= numbers.length-1; while(itarget){ j--; }else if((numbers[i]+numbers[j])

推荐信息