【LeetCode】面试题57. 和为s的两个数字(JAVA)

原题地址:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/

题目描述:
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。

示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]

示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]

限制:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6

解题方案:
昨天做的类似的题,但是是无序的,需要用哈希表,但是有序只要用双指针从两边向中间找就可以了。

代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int head = nums.length - 1, tail = 0;
        while(nums[head] + nums[tail] != target)
        {
            while(nums[head] + nums[tail] < target)
                tail ++;
            while(nums[head] + nums[tail] > target)
                head --;
        }
        return new int[]{nums[tail], nums[head]};
    }
}
发布了110 篇原创文章 · 获赞 4 · 访问量 9319

猜你喜欢

转载自blog.csdn.net/rabbitsockx/article/details/104693524