Leetcode167. Two Sum II - Input array is sorted

    xiaoxiao2021-12-14  17

    原题 Given an array of integers that is already sorted in ascending order, 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 思路 要求:给出一个升序整数数组,找到两个数字,使得加起来达到特定的目标数,注意返回两个数字的索引(索引下标是从1开始的) 思路:1、使用两个指针,双层遍历数组,直至数组中出现两个数的和是目标数,但是这样容易超时,效率低下 代码1

    public class Solution { public int[] twoSum(int[] numbers, int target) { for(int i=0;i<numbers.length;i++){ for(int j=i+1;j<numbers.length;){ if(numbers[i]+numbers[j]<target) j++; else if(numbers[i]+numbers[j]==target) { return new int[]{i+1,j+1}; } else break; } } return null; } }

    代码2 思路2,使用数组的一个方法二分搜索算法查找值

    public class Solution { public int[] twoSum(int[] numbers, int target) { for(int i=0,n=numbers.length;i<n;i++){ //采用二分搜索算法查找值V,如果查找成功,则返回相应的下标值,否则返回一个负数 int j=Arrays.binarySearch(numbers,i+1,numbers.length,target-numbers[i]); if(j>0) return new int []{i+1,j+1}; } return null; } }

    但是这两种方法效率都不是太高。 原题链接

    转载请注明原文地址: https://ju.6miu.com/read-962693.html

    最新回复(0)