当前位置:网站首页>leetcode 剑指 Offer 57. 和为s的两个数字
leetcode 剑指 Offer 57. 和为s的两个数字
2022-07-30 08:52:00 【kt1776133839】
题目描述:
输入一个递增排序的数组和一个数字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
解题思路:
利用 HashMap 可以通过遍历数组找到数字组合,时间和空间复杂度均为 O(N);
注意本题的 nums 是 排序数组 ,因此可使用 双指针法 将空间复杂度降低至 O(1) 。
算法流程:
初始化: 双指针 i , j 分别指向数组 nums 的左右两端 (俗称对撞双指针)。
循环搜索: 当双指针相遇时跳出;
计算和 s=nums[i]+nums[j] ;
若 s>target ,则指针 j 向左移动,即执行 j=j−1 ;
若 s<target ,则指针 i 向右移动,即执行 i=i+1 ;
若 s=target ,立即返回数组 [nums[i],nums[j]] ;
返回空数组,代表无和为 target 的数字组合。
class Solution {
public int[] twoSum(int[] nums, int target) {
int i = 0, j = nums.length - 1;
while(i < j) {
int s = nums[i] + nums[j];
if(s < target) i++;
else if(s > target) j--;
else return new int[] { nums[i], nums[j] };
}
return new int[0];
}
}
边栏推荐
猜你喜欢

How to implement Golang DES encryption and decryption?

An article to understand service governance in distributed development

信号完整性测试

How to Assemble a Registry

百度paddleocr检测训练

Using IN in MySQL will not go through index analysis and solutions

Test automation selenium (a)

读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》

新手必备!最全电路基础知识讲解

一个低级错误导致的诡异现象——走近科学能拍三集,(C语言)最简单的数组元素读取,不正确!?
随机推荐
经历了这样一个阶段的发展之后,数字零售才能有新的进化
HCIP - MPLS VPN experiment
Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
如何避免CMDB沦为数据孤岛?
一文读懂二十种开关电源拓扑结构
leetcode 剑指 Offer 42. 连续子数组的最大和
Two solutions for Excel xlsx file not supported
电路分析:运放和三极管组成的恒流源电路
Explain the problem of change exchange in simple terms - the shell of the backpack problem
用示波器揭示以太网传输机制
【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作
仿牛客网项目第二章:开发社区登录模块(详细步骤和思路)
Jenkins 如何玩转接口自动化测试?
qsort 函数的使用及其模拟实现
SRAM与DRAM的区别
积分简明笔记-第一类曲线积分的类型
Scala
Windows 下安装 MySQL
Activating data potential Amazon cloud technology reshapes cloud storage "family bucket"
02-课程发布