title: Daily practice (29): and two numbers with s
categories:[Swords offer]
tags:[Daily practice]
date: 2022/03/02
Daily practice (29): and two numbers for s
Given an array sorted in increasing order and a number s, find two numbers in the array such that their sum is exactly s. If the sum of multiple pairs of numbers is equal to s, just output any pair.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [2,7] or [7,2]
Example 2:
Input: nums = [10,26,30,31,47,60], target = 40
Output: [10,30] or [30,10]
limit:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
Source: LeetCode
Link: https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof
Method 1: Hash
Ideas:
- Create a hash table
- iterate over the array
- If the sum of the element in the hash table and the element currently traversed is target, the result can be returned
- There are no elements that satisfy the condition, return null
vector<int> twoSum(vector<int>& nums, int target) {
// 创建哈希表
unordered_set<int> s;
// 遍历数组
for (int x : nums) {
// 若哈希表中存在元素与当前遍历到的元素之和为target
// 则返回结果即可
if (s.count(target - x)) {
return vector<int>{x, target - x};
}
// 插入当前遍历到的元素
s.insert(x);
}
// 没有满足条件的元素,返回空
return {};
}
Method 2: Double pointer
Taking full advantage of the nature of the incrementing array, the double pointer is traversed from the beginning and the end. If the sum of the two numbers is less than the target, then left++; if it is greater than the target, then right--.
vector<int> twoSum(vector<int>& nums, int target) {
int l = 0; int r = nums.size() - 1;
while (l < r) {
if (target == nums[l] + nums[r]) {
return vector<int>{nums[l], nums[r]};
}
else if (target > nums[l] + nums[r]) {
l++;
}
else if (target < nums[l] + nums[r]) {
r--;
}
}
return vector<int>();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。