iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 1
0
Software Development

LeetCode小試身手系列 第 1

【Day 1】#1 - Two Num

題目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
 
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解析

此題要求從一個數字陣列中取出其中兩個數字,這兩個數字的和剛好等於指定的值(target)。
若採用雙迴圈暴力法依序從第一個數字判斷與其他數字加總是否符合,則時間複雜度為O(N²)。

更好的方法是使用HashMap來達到時間複雜度只要O(N),具體做法為依序從第一個數字(nums[i])開始,算出目標值(target)減去該數字所得到的差值(target-num[i]),查看該差值是否存在於HashMap裡,若不存在,則將該差值及其索引存進HashTable;若存在,則回傳當下數字(nums[i])及差值(target-nums[i])的索引。

解法

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

心得

此題重點在於能想到使用HashTable使時間複雜度最小化,因此要能夠理解Array及HashTable在搜尋上的時間複雜度差異,以及HashTable的使用語法。


希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。


下一篇
【Day 2】#1176 - Diet Plan Performance
系列文
LeetCode小試身手14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言