LeetCode日记——【算法】双指针专题

  题1:两数之和 II - 输入有序数组(Two Sum II - Input array is sorted)

Leetcode题号:167

难度:Easy

链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/

题目描述:

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

说明:

返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

代码:

 1 class Solution {
 2     public int[] twoSum(int[] numbers, int target) {
 3         if(numbers==null) return null;
 4         int i=0,j=numbers.length-1;
 5         while(i<j){
 6             int sum = numbers[i]+numbers[j];
 7             if(sum==target) {
 8                 return new int[]{i + 1, j + 1};
 9             }else if(sum<target){
10                 i++;
11             }else{
12                 j--;
13              }
14         }
15         return null;
16     }
17 }

分析:

我们使用两个指针,初始分别位于第一个元素和最后一个元素位置,比较这两个元素之和与目标值的大小。如果和等于目标值,我们发现了这个唯一解。如果比目标值小,我们将较小元素指针增加一。如果比目标值大,我们将较大指针减小一。移动指针后重复上述比较知道找到答案。
写代码的时候尽量简略,如new int [ ] {i+1,j+1}。
 

  题2:两数平方和(Sum of Square Numbers)

Leetcode题号:633

难度:Easy

链接:https://leetcode-cn.com/problems/sum-of-square-numbers/description/

题目描述:

给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。

例1:

输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5

示例2:

输入: 3
输出: False

猜你喜欢

转载自www.cnblogs.com/augenstern/p/12913187.html
今日推荐