有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何确定列表中是否有2个元素提供了sum?

在面试中,我被要求按照以下合同编写方法:

boolean checkList(List<Long> list, long sum){...}

例如,它必须为参数返回true
({1,2,3,4,5,6}9)因为4+5=9

对于参数,它必须返回false

({0,10,30}11),因为没有2个元素与和11的组合

我建议这样的代码:

boolean checkList(List<Long> list, long expectedSum) {
    if (list.size() < 2) {
        return false;
    }
    for (int i = 0; i < list.size() - 1; i++) {
        for (int k = i; k < list.size(); k++) {
            if ((list.get(i) + list.get(k)) == expectedSum) {
                return true;
            }
        }
    }
    return false;
}

但面试官让我再实施一个解决方案

我无法创建更好的解决方案。你能吗


共 (4) 个答案

  1. # 1 楼答案

    也给散列一个机会。这个问题有更多的解决方案

    // Java implementation using Hashing 
    import java.io.*; 
    import java.util.HashSet; 
    
    class PairSum 
    { 
        static void printpairs(int arr[],int sum) 
        {        
            HashSet<Integer> s = new HashSet<Integer>(); 
            for (int i=0; i<arr.length; ++i) 
            { 
                int temp = sum-arr[i]; 
    
                // checking for condition 
                if (temp>=0 && s.contains(temp)) 
                { 
                    System.out.println("Pair with given sum " + 
                                        sum + " is (" + arr[i] + 
                                        ", "+temp+")"); 
                } 
                s.add(arr[i]); 
            } 
        } 
    
        // Main to test the above function 
        public static void main (String[] args) 
        { 
            int A[] = {1, 4, 45, 6, 10, 8}; 
            int n = 16; 
            printpairs(A,  n); 
        } 
    } 
    
  2. # 2 楼答案

    试试这个

       public static boolean checklist(List<Long> list, long expectedSum) {
        if(list.size() < 2) {
            return false;
        }
        HashSet<Long> hs = new HashSet<Long>();
        for(long i : list) {
            hs.add(i);
        }
    
        for(int i=0; i< list.size(); i++) {
            if(hs.contains(expectedSum - list.get(i))) {
                return true;
            }
        }
        return false;
    }
    
  3. # 3 楼答案

    也许看看每个数字,看看总数减去这个数字是否在列表中 所以

    boolean checkList(List<Long> list, long expectedSum) {
        if (list.size() < 2) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            if(list.contains(expectedSum-list.get(i))){
                return true;
            }
        }
        return false;
    }
    
  4. # 4 楼答案

    一个使用java-8的衬里:

    public boolean checkList(List<Long> list, long expectedSum) {
        Set<Long> hashSet = new HashSet<>(list);
        return IntStream.range(0, list.size())
                        .anyMatch(i -> hashSet.contains(expectedSum - list.get(i)));
    }