力扣633-平方数之和

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

class Solution {
    public boolean judgeSquareSum(int c) {
        int i=0;
        int j=(int)Math.sqrt(c);
        while(i<=j){
            if(i*i+j*j==c){
                return true;
            }else if(i*i+j*j>c){
                j--;
            }else{
                i++;
            }
        }
        return false;
    }
}

 

### LeetCode 'Two Sum' 的 Java 实现 以下是针对 LeetCode 上经典的 'Two Sum' 问题的一种高效解决方案,基于哈希表(`HashMap`)。这种方法的时间复杂度为 O(n),空间复杂度也为 O(n)[^1]。 #### 使用 `HashMap` 解决方案 通过使用 `HashMap` 来存储数组中的元素及其索引位置,可以快速查找目标差值是否存在于已遍历过的数据中。如果存在,则可以直接返回对应的两个索引。 ```java import java.util.HashMap; public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; if (numbers == null || numbers.length < 2) { return result; } HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { if (!map.containsKey(target - numbers[i])) { map.put(numbers[i], i); } else { result[0] = map.get(target - numbers[i]) + 1; result[1] = i + 1; break; } } return result; } } ``` 上述代码逻辑如下: - 遍历输入数组的同时,计算当前数值与目标值之间的差值。 - 如果该差值已经存在于 `HashMap` 中,则说明找到了符合条件的一对数;否则将当前数值存入 `HashMap` 并继续迭代。 此方法利用了哈希表的常量级查询时间特性来优化性能[^3]。 另外还有一种较为简单的暴力枚举法,虽然效率较低但易于理解: #### 暴力枚举法 对于每一对可能组合逐一验证是否满足条件即可得到结果。不过由于嵌套循环的存在使其整体运行时间为平方级别即O(n²)[^4]: ```java class BruteForceSolution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; ++i){ for (int j = i + 1; j < nums.length; ++j){ if ((nums[i] + nums[j]) == target ){ return new int[]{i,j}; } } } throw new IllegalArgumentException("No two sum solution"); } } ``` 尽管如此,在实际应用当中更推荐采用前者的做法以获得更好的执行效果。 --- ### 输入输出示例 假设我们有以下测试案例: **Example Input:** `numbers={2, 7, 11, 15}`, `target=9` **Expected Output:** `index1=1`, `index2=2` [^5] 这意味着第一个匹配到的有效整数位于原始列表下标为零的位置(因为是从1开始计数),而第二个则处于紧随其后的下一个槽位上. ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值