1. 程式人生 > >1. Two Sum - LeetCode

1. Two Sum - LeetCode

rip lB num 其他 思路 int href 簡單 integer

Question

1. Two Sum

技術分享圖片

Solution

思路很簡單這裏就不說了,下面貼了不同的幾個Java實現的時間與其他算法實現的時間的比較

這個是LeetCode的第一道題,也是我刷的第一道,剛一開始的Java實現

public int[] twoSum(int[] nums, int target) {
    boolean find = false;
    int targeti = -1, targetj = -1;
    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums.length
; j++) { if (i == j) { continue; } if (nums[i] + nums[j] == target) { targeti = i; targetj = j; find = true; break; } } if (find) { break; } } return
new int[]{targeti, targetj}; }

技術分享圖片

稍微改進一下

public int[] twoSum(int[] nums, int target) {
    boolean find = false;
    int targeti = -1, targetj = -1;
    for (int i = 0; i < nums.length - 1; i++) {
        for (int j = i + 1; j < nums.length; j++) {

            if (nums[i] + nums[j] == target) {
                targeti = i;
                targetj = j;
                find = true
; break; } } if (find) { break; } } return new int[]{targeti, targetj}; }

技術分享圖片

下面這個版本是在討論中看到的O(1)時間復雜度

public int[] twoSum3(int[] nums, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(target - nums[i])) {
            result[1] = i;
            result[0] = map.get(target - nums[i]);
            return result;
        }
        map.put(nums[i], i);
    }
    return result;
}

技術分享圖片

1. Two Sum - LeetCode