找出數組中兩數之和為指定值的所有整數對


一,問題描述

給定一個整型數組(數組中的元素可重復),以及一個指定的值。打印出數組中兩數之和為指定值的 所有整數對

 

二,算法分析

一共有兩種方法來求解。方法一借助排序,方法二采用HashSet

方法一:

先將整型數組排序,排序之后定義兩個指針left和right。left指向已排序數組中的第一個元素,right指向已排序數組中的最后一個元素

將 arr[left]+arr[right]與 給定的元素比較,若前者大,right--;若前者小,left++;若相等,則找到了一對整數之和為指定值的元素。

此方法采用了排序,排序的時間復雜度為O(NlogN),排序之后掃描整個數組求和比較的時間復雜度為O(N)。故總的時間復雜度為O(NlogN)。空間復雜度為O(1)

 

方法二:

依次遍歷整型數組,對整型數組中的每一個元素,求解它的suplement(expectedSum-arr[i]).suplement就是指定的值減去該數組元素。

如果該元素的 suplement不在HashSet中,則將該元素添加到HashSet。

如果該元素的suplement在HashSet中,說明已經找到了一對整數之和為指定值的元素。

該方法使用了HashSet,故空間復雜度為O(N),由於只需要掃描一遍整型數組,故時間復雜度為O(N)

 

三,完整代碼實現:

import java.util.Arrays;
import java.util.HashSet;

public class ExpectSumOfTwoNumber {
    
    public static void expectSum_bySort(int[] arr, int expectSum)
    {
        if(arr == null || arr.length == 0)
            return;
        Arrays.sort(arr);
        int left = 0, right = arr.length - 1;
        
        while(left < right)
        {
            if(arr[left] + arr[right] > expectSum)
                right--;
            else if(arr[left] + arr[right] < expectSum)
                left++;
            else//equal
            {
                System.out.println(arr[left] + " + " + arr[right] + " = " + expectSum); 
                left++;
                right--;
            }
        }
    }
    
    
    public static void expectSum_bySet(int[] arr, int expectSum)
    {
        if(arr == null || arr.length == 0)
            return;
        HashSet<Integer> intSets = new HashSet<Integer>(arr.length);
        
        int suplement;
        for (int i : arr)
        {
            suplement = expectSum - i;
            if(!intSets.contains(suplement)){
                intSets.add(i);
            }else{
                System.out.println(i + " + " + suplement + " = " + expectSum);
            }
        }
    }
    
    //hapjin test
    public static void main(String[] args) {
        int[] arr = {2,7,4,9,3};
        int expectSum = 11;
        expectSum_bySet(arr, expectSum);
        System.out.println("************");
        expectSum_bySort(arr, expectSum);
        System.out.println("----------------");
        int[] arr2 = {3,7,9,1,2,8,5,6,10,5};
        int expectSum2 = 10;
        expectSum_bySet(arr2, expectSum2);
        System.out.println("**********");
        expectSum_bySort(arr2, expectSum2);
    }
}

 

原文:http://www.cnblogs.com/hapjin/p/5746659.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM