两数之和-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++;
            }
        }
发布了18 篇原创文章 · 获赞 0 · 访问量 676

猜你喜欢

转载自blog.csdn.net/qq_42060170/article/details/104105218