CS-Notes/notes/57.1 和为 S 的两个数字.md
2020-11-04 02:18:54 +08:00

41 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 57.1 和为 S 的两个数字
## 题目链接
[牛客网](https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tqId=11195&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
在有序数组中找出两个数使得和为给定的数 S如果有多对数字的和等于 S输出两个数的乘积最小的
## 解题思路
使用双指针一个指针指向元素较小的值一个指针指向元素较大的值指向较小元素的指针从头向尾遍历指向较大元素的指针从尾向头遍历
- 如果两个指针指向元素的和 sum == target那么这两个元素即为所求
- 如果 sum > target移动较大的元素使 sum 变小一些
- 如果 sum < target移动较小的元素使 sum 变大一些
```java
public ArrayList<Integer> FindNumbersWithSum(int[] nums, int target) {
int i = 0, j = nums.length - 1;
while (i < j) {
int cur = nums[i] + array[j];
if (cur == target)
return new ArrayList<>(Arrays.asList(nums[i], nums[j]));
if (cur < target)
i++;
else
j--;
}
return new ArrayList<>();
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>