当前位置:网站首页>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];
}
}
边栏推荐
- 2022杭电多校第二场
- 2022 Hangzhou Electric Multi-School 2nd Game
- The difference between DDR, GDDR, QDR
- els 方块、背景上色
- Integral Special Notes - Definition of Integral
- C# 之 $ – 字符串内插
- 研发人员的悲剧——“庞氏骗局”
- One article to understand twenty kinds of switching power supply topologies
- MySQL中使用IN 不会走索引分析以及解决办法
- 2022 Hangzhou Electric Multi-School 1st Game
猜你喜欢

自动化测试selenium(一)

瑞吉外卖项目(五) 菜品管理业务开发

20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission

TreeSet解析

SRAM与DRAM的区别

TreeSet parsing

Devops和低代码的故事:螳螂捕蝉,黄雀在后

pnpm简介

Concise Notes on Integrals - Types of Curve Integrals of the Second Kind

编程界的“躲猫猫”比赛 | 每日趣闻
随机推荐
C# 之 $ – 字符串内插
用示波器揭示以太网传输机制
Kotlin 值类 - value class
仿牛客网项目第一章:开发社区首页(详细步骤和思路)
知识图谱之Cypher语言的使用
Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
HCIP --- MPLS VPN实验
信号完整性测试
An article to understand service governance in distributed development
积分专题笔记-与路径无关条件
Test automation selenium (a)
研发人员的悲剧——“庞氏骗局”
echart图表清空上一次数据
微软 SQL 服务器被黑,带宽遭到破坏
一文理解分布式开发中的服务治理
无法定位程序输入点ucrtbase.abort于动态链接库api-ms-win-crt-runtime-|1-1-0.dll上
Functional Interfaces & Lambda Expressions - Simple Application Notes
积分专题笔记-曲线面积分三大公式
MySQL数据库题库
负电压电路(原理分析)