前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-面试题57-和为s的两个数字

LeetCode-面试题57-和为s的两个数字

作者头像
benym
发布2022-07-14 15:42:18
1440
发布2022-07-14 15:42:18
举报
文章被收录于专栏:后端知识体系后端知识体系

# LeetCode-面试题57-和为s的两个数字

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

示例1:

代码语言:javascript
复制
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]

示例 2:

代码语言:javascript
复制
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]

限制:

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6

# 解题思路

查找思想:

一个头指针一个尾指针,在递增排序的数组中,

如果对应位置之和大于target,说明需要取小一点,左移尾指针让数值变小

如果对应位置之和小于target,说明需要取大一点,右移头指针,让数值变大

# Java代码

代码语言:javascript
复制
class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums==null||nums.length<=0)
            return new int[0];
        int start = 0;
        int end = nums.length-1;
        while(start<end){
            if(nums[start]+nums[end]<target)
                start+=1;
            else if(nums[start]+nums[end]>target)
                end-=1;
            else
                return new int[]{nums[start],nums[end]};
        }
        return new int[0];
    }
}

# Python代码

代码语言:javascript
复制
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        start,end = 0,len(nums)-1
        while start<end:
            if nums[start]+nums[end]>target:
                end-=1
            elif nums[start]+nums[end]<target:
                start+=1
            else: return nums[start],nums[end]
        return []
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # LeetCode-面试题57-和为s的两个数字
    • # 解题思路
      • # Java代码
        • # Python代码
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档