iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
2
Software Development

前端工程師用 javaScript 學演算法系列 第 24

[LeetCode #1064] Binary Search

1064. Fixed Point

// Question:
// Given an array A of distinct integers sorted in ascending order, return the smallest index i // that satisfies A[i] == i.  Return -1 if no such i exists.
// 給一個裡面都包含不同數字的陣列 A,排序已經由小到大排好了。請找出符合 A[i] = i 的值
// Example:
Input: [-10,-5,0,3,7]
Output: 3
Explanation: 
For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3.
Example 2:

Input: [0,2,5,8,17]
Output: 0
Explanation: 
A[0] = 0, thus the output is 0.
Example 3:

Input: [-10,-5,3,4,7,9]
Output: -1
Explanation: 
There is no such i that A[i] = i, thus the output is -1.
 * @param {number[]} A
 * @return {number}
 */
var fixedPoint = function (A) {

}

Think

極限值/特殊狀況

可能會有兩種以上答案,例如這種 [-10, -5, -2, 0, 4, 5, 6, 7, 8, 9, 10],題目說選最小的為 output

哪種資料結構解

有順序姓而且明顯是在搜尋,所以會用 Array,而且 input 有順序而且又是找東西,所以會用 Binary Search

大概會怎麼解

這題比較特別的是有可能會有一種以上答案,所以會先定義 minIndex 存最小的值。

let minIndex = Number.MAX_SAFE_INTEGER;

其他部分單純用 Binary Search 解
https://ithelp.ithome.com.tw/upload/images/20190925/20106426lkSShPTKhM.jpg

mid = Math.floor((start + end) / 2); // 從中間開始找
if (mid < A[mid]) { // 2 < 0
    // 往左找      
    end = mid - 1;
} else if (mid > A[mid]) { // 2 > 0
    // 往右找
    start = mid + 1 // start = 3
} else {
    minIndex = Math.min(minIndex, mid);
    end = mid - 1;
};

https://ithelp.ithome.com.tw/upload/images/20190925/20106426XENg90LBL7.jpg

完整程式碼

var fixedPoint = function (A) {
    const len = A.length;
    let minIndex = Number.MAX_SAFE_INTEGER;
    if (len < 1) return -1;

    // 這邊都以 index 為單位
    let start = 0;
    let end = len - 1;

    //  從中間開始切
    let mid;

    while (start <= end) {
        mid = Math.floor((start + end) / 2);
        console.log('mid: ' + mid)
        if (mid < A[mid]) { 
            // 往左找      
            end = mid - 1;
        } else if (mid > A[mid]) { 
            // 往右找
            start = mid + 1 
        } else {
            minIndex = Math.min(minIndex, mid);
            end = mid - 1;
        };
    }
    // 如果上面都不符合代表找不到
    return (minIndex == Number.MAX_SAFE_INTEGER) ? -1 : minIndex;

};


console.log(fixedPoint([-10, -5, -2, 0, 4, 5, 6, 7, 8, 9, 10]))
如有錯誤或需要改進的地方,拜託跟我說。
我會以最快速度修改,感謝您

歡迎追蹤我的部落格,除了技術文也會分享一些在矽谷工作的甘苦。


上一篇
簡易搜尋 Sequential Search & 二分搜尋 Binary Search
下一篇
遞迴 Recursion
系列文
前端工程師用 javaScript 學演算法32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
mwsmartin2014
iT邦新手 5 級 ‧ 2019-09-25 11:28:46

同樣是web developer不過我是搞full stack的,同樣想去國外找工作,同樣對algorithm不熟識,慚愧的是我當年大學時還教的很深入的可是我都不好好讀,靠著其他課拉高分混過去。悔不當初,現在重溫data structure和algorithm階段剛好就被我看到博主,有同路人真好。
另外建議一下以後找一篇寫一下怎樣計算Time/Space complexity,以我經驗基本上會問算法的公司都會叫你計算一下你解法的BigO
/images/emoticon/emoticon02.gif

hannahpun iT邦新手 4 級 ‧ 2019-09-25 11:47:50 檢舉

好喔 謝謝建議,我也好想回學校去修看看這門課啊
現在真的光想出解法就花好多時間了,還要求比較佳的解法,還是需要再努力一點

我要留言

立即登入留言