目 录CONTENT

文章目录

75. 和为S的两个数字

Gz
Gz
2022-07-01 / 0 评论 / 0 点赞 / 164 阅读 / 709 字 / 正在检测是否收录...

75. 和为S的两个数字

输入一个数组和一个数字 ss,在数组中查找两个数,使得它们的和正好是 ss。

如果有多对数字的和等于 ss,输出任意一对即可。

你可以认为每组输入中都至少含有一组满足条件的输出。

数据范围

数组长度 [1,1002][1,1002]。

样例

输入:[1,2,3,4] , sum=7

输出:[3,4]

题解(暴力)

class Solution {
    public int[] findNumbersWithSum(int[] nums, int target) {
        int a[] = new int[2];
        for(int i = 0 ; i < nums.length ; i ++) {
            for (int j = 0 ; j < nums.length-1 ; j ++) {
                if (nums[i] + nums[j] == target){
                    
                    if (nums[i] > nums[j]) return new int[]{nums[j],nums[i]};
                    else return new int[] {nums[i],nums[j]};
                }
            }
        }
        return null;

    }
}

题解(HashSet)

//边存边比较
class Solution {
    public int[] findNumbersWithSum(int[] nums, int target) {
        if(nums==null || nums.length<=1) return null;
        Set<Integer> set=new HashSet();
        for(int num:nums){
            int t=target-num;
            if(set.contains(t)){
                return new int[]{num,t};
            }else{
                set.add(num);
            }
        }
        return null;
    }
}
0

评论区