两数之和及其变体

lc第一题 两数之和

科大讯飞2023.7.29笔试

现在给定一个目标数target,一个数组arr,数组表示雷点,即组成target的两个数x,y不能出现在这个数组中,请求出有多少种方案组成target?

数据范围:
-10^9 <= target, arr[i]<=10^9
1<=x,y<=target

例子:
输入:target=10,arr=[1,2,3]
结果:3

方法一:

import java.util.HashSet;
import java.util.Set;

public class XunFei {
    
    

    public static void main(String[] args) {
    
    
        int[]a=new int[]{
    
    1,2,3,4,6};
        System.out.println(getVal(a,10));
    }

    public static int getVal(int[]arr,int t){
    
    
        int cnt=0;
        Set<Integer> s=new HashSet<>();
        int total=arr.length;
        
        for(int i=0;i<arr.length;i++){
    
    
     
            if(arr[i]>=t){
    
    
                total--;
                continue;
            }
            s.add(arr[i]);
            if(s.contains(t-arr[i])){
    
    
                cnt++;
            }

        }

        return t-1-cnt*2-(total-cnt*2)*2;
    }
}

方法二:(简约版本)

  import java.util.*;
    public class Main {
    
    
        public static void main(String[] args) {
    
    
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int[] a = new int[n];
            Set<Integer> st = new HashSet<>();
            for(int i = 0 ; i < n ; i ++) {
    
    
                a[i] = sc.nextInt();
            }
            int s = sc.nextInt();
            for(int t: a) {
    
    
                if(t < s) {
    
    
                    st.add(t); #相当于在set中添加(t, s-t)对
                    st.add(s-t); #相当于添加(s-t, t)}
            }
            System.out.println(s - 1 - st.size());
        }
    }

猜你喜欢

转载自blog.csdn.net/yxg520s/article/details/132000431