兩數之和-I

問題:給定一個整型數組,是否能找出其中的兩個數使其合爲某個指定 的值?
思路:排序後,從數組兩端向中間移動,一次移動一端的指針,直至兩數合爲爲指定值。
java實現:

boolean hasSum(int[] A,int target) {
        boolean res = false;
        if (A == null || A.length < 2)
            return res;
        Arrays.sort(A);
        int i = 0, j = A.length - 1;
        while (i < j) {
            if (A[i] + A[j] == target) {
                res = true;
                break;
            } else if (A[i] + A[j] > target) {
                j--;
            } else {
                i++;
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章