两数之和-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++;
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章