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