【双指针】Leetcode --- NO.633 平方数之和(Java)

题目描述

在这里插入图片描述

题目分析

  • 这道题跟两数之和异曲同工,关键在于如何取尾指针的数
  • 因为平方数中,只有 02 是最小的,仍为0,假定头指针的数为0 ,那么尾指针最大的数即为 target的开方,这个可以使用Math.sqrt()来计算
  • 确定了尾指针的值过后,就跟两数之和的解法是一样的了

解法分析

  • 因为题目中没有提到 a2 不能和 b2 相等,所以这里的头指针和尾指针是可以重合的
  • 仍然使用while循环,直到两个指针相遇

代码

class Solution {
    public boolean judgeSquareSum(int target) {
    	// 如果目标值小于0 直接返回false
        if (target < 0) return false;
        // 头指针
        int head = 0;
        // 尾指针
        int end = (int) Math.sqrt(target);
        // 循环遍历,直到两个指针相遇 可以重合,所以是 <=
        while (head <= end){
        	// 计算当前的和
            int sum = head*head+end*end;
            // 相等返回 true
            if (sum == target){
                return true;
            } else if (sum > target){
            	// 变大则尾指针前移
                end--;
            } else {
            	// 偏小则头指针后移
                head++;
            }
        }
        // 找不到则返回false
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/Kobe_k/article/details/107442812
今日推荐