和为s的两个数字

一:题目描述:

二:Code:

两种方法:

import java.util.Arrays;

import org.junit.Test;

public class totalArray {
    public void printResult(int a, int b) {
        System.out.println(a + "+" + b);
    }

    // 时间复杂度O(n^2)
    public void twoSum(int[] array, int s) {
        int len = array.length;
        for (int i = 0; i <= len - 1; i++) {
            for (int j = i + 1; j <= len - 1; j++) {
                if (array[i] + array[j] == s) {
                    printResult(array[i], array[j]);
                    break;
                }
            }
        }
    }

    //// 时间复杂度为线性 
    public void twoSum02(int[] array, int s) {
        int i = 0;
        int j = array.length - 1;
        while (i < j) {
            int sum = array[i] + array[j];
            if (sum == s) {
                printResult(array[i], array[j]);
                i++;
                j--;
            } else if (sum > s) {
                j--;
            } else {
                i++;
            }
        }
    }

    // 给定的数组已经排好序了,所以用二分查找,时间复杂度为O( nlog(n) )
    public void twoSum03(int[] array, int s) {
        int n = array.length;
        for (int i = 0; i < n - 1; i++) {
            int another = s - array[i];
            if (Arrays.binarySearch(array, i + 1, n, another) >= i + 1) {
                printResult(array[i], another);
            }
        }
    }

    @Test
    public void testTwosum() {
        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int s = 10;
        twoSum03(array, s);
    }
}
发布了89 篇原创文章 · 获赞 100 · 访问量 16万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章