Binary Search

LC34. Find First and Last Position of Element in Sorted Array
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

 public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        if (nums.length == 0 || nums == null) return res;
        int start = 0, end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] == target) end = mid;
            else if (nums[mid] > target) end = mid;
            else start = mid;
        }
        if (nums[start] == target) res[0] = start;
        else if (nums[end] == target) res[0] = end;
        else res[0] = -1;
        
        start = 0;
        end = nums.length - 1;
         while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] == target) start = mid;
            else if (nums[mid] > target) end = mid;
            else start = mid;
        }
        if (nums[end] == target) res[1] = end;
        else if (nums[start] == target) res[1] = start;
        else res[1] = -1;
        return res;
    }

LC35. Search Insert Position
Input: [1,3,5,6], 5
Output: 2

 public int searchInsert(int[] nums, int target) {
        if (target < nums[0]) return 0;
        //find  the first element which >= target int the array
        // first element 先比較start西篓, last element比較end
        int start = 0, end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] == target){
                return mid;
            } else if (nums[mid] > target){
                end = mid;
            } else {
                start = mid;
            }
        }
         if (nums[start] >= target) return start;
         else if (nums[end] >= target) return end;
         else return end + 1;
    }

LC74. Search a 2D Matrix
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true

//二分查找法的解題步驟莹弊,先看題目要求是求first position of element >或< target,還是
    //last position of element >或< target.如果是first那就判斷條件時(shí)先start >或< target再end >或< target谒拴。統(tǒng)一格式捐迫,判定條件泳叠,start + 1 < end吼过, start和end都是mid城菊,循環(huán)完之后谊路,
//根據(jù)具體條件看是start開(kāi)始還是end開(kāi)始传于。O(logn + logm)
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        if (matrix[0] == null || matrix[0].length == 0) return false;
        // last of position <= target;
        int m = matrix.length;
        int row = 0;
        int start = 0, end = m - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (matrix[mid][0] == target) return true;
            else if (matrix[mid][0] < target) start = mid;
            else end = mid;
        }
        if(matrix[end][0] <= target) row = end;
        else if (matrix[start][0] <= target) row = start;
        
        start = 0;
        end = matrix[row].length - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (matrix[row][mid] == target) return true;
            else if (matrix[row][mid] < target) start = mid;
            else end = mid;
        }
        if (matrix[row][start] == target) return true;
        else if (matrix[row][end] == target) return true;
        else return false;
    }
  1. Search a 2D Matrix II
    [
    [1, 4, 7, 11, 15],
    [2, 5, 8, 12, 19],
    [3, 6, 9, 16, 22],
    [10, 13, 14, 17, 24],
    [18, 21, 23, 26, 30]
    ]
    Given target = 5, return true.
    Given target = 20, return false.
//We start search the matrix from top right corner, initialize the current position to top right corner, if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than the value in current position, then the target can not in the entire column because the column is sorted too. We can rule out one row or one column each time, so the time complexity is O(m+n).
 public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
        int col = matrix[0].length - 1;
        int row = 0;
        while (col >= 0 && row <=matrix.length - 1){
            if (matrix[row][col] == target) return true;
            else if (matrix[row][col] > target) col--;
            else row++;
        }
        return false;
    }

LC162. Find Peak Element
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.

public int findPeakElement(int[] nums) {
        if (nums.length == 0 || nums == null) return 0;
        int start = 0, end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start)/2;
            if (nums[mid] < nums[mid-1]){
                end = mid;
            } else if (nums[mid] < nums[mid + 1]){
                start = mid;
            } else {
                end = mid;
            }
        }
        return nums[start] < nums[end] ? end : start;
    }

LC153. Find Minimum in Rotated Sorted Array
Input: [3,4,5,1,2]
Output: 1

 // first postion 比前一個(gè)小囱挑,二分法
    // 45678123,中點(diǎn)和end進(jìn)行比較!U恿铩平挑!比end大,范圍所小到mid系草,end
    // 78123456,中點(diǎn)和end進(jìn)行比較Mㄏā!找都!比end小唇辨,范圍縮小到start,mid
    //最后在節(jié)點(diǎn)start和end縮小到前后兩個(gè)時(shí)候能耻,比較前后的大小赏枚,誰(shuí)小輸出結(jié)果就是誰(shuí)
    public int findMin(int[] nums) {
        int start = 0, end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start)/2;
            if (nums[mid] > nums[end]){
                start = mid;
            } else {
                end = mid;
            }
        }
        if (nums[start] < nums[end]) return nums[start];
        else return nums[end];
    }

LC33. Search in Rotated Sorted Array
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

// 針對(duì)rotated這類問(wèn)題亡驰。想象在14象限的兩條直線。
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;
        int start = 0, end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start)/2;
            if (nums[mid] == target) return mid;
            if (nums[mid] > nums[start]){
                if(target < nums[mid] && target >= nums[start]){
                    end = mid;
                } else {
                    start = mid;
                }
            } else if (nums[mid] < nums[end]){
                if (target <= nums[end] && target > nums[mid]){
                    start = mid;
                } else {
                    end = mid;
                }
            }
        }
        if (nums[start] == target) return start;
        else if (nums[end] == target) return end;
        
        return -1;
   }

LC4. Median of Two Sorted Arrays
nums1 = [1, 3]
nums2 = [2]
The median is 2.0

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末饿幅,一起剝皮案震驚了整個(gè)濱河市凡辱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌栗恩,老刑警劉巖透乾,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異磕秤,居然都是意外死亡乳乌,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)市咆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)钦扭,“玉大人,你說(shuō)我怎么就攤上這事床绪】颓椋” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵癞己,是天一觀的道長(zhǎng)膀斋。 經(jīng)常有香客問(wèn)我,道長(zhǎng)痹雅,這世上最難降的妖魔是什么仰担? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮绩社,結(jié)果婚禮上摔蓝,老公的妹妹穿的比我還像新娘。我一直安慰自己愉耙,他們只是感情好贮尉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著朴沿,像睡著了一般猜谚。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赌渣,一...
    開(kāi)封第一講書(shū)人閱讀 51,521評(píng)論 1 304
  • 那天魏铅,我揣著相機(jī)與錄音,去河邊找鬼坚芜。 笑死览芳,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的鸿竖。 我是一名探鬼主播沧竟,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼铸敏,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了屯仗?” 一聲冷哼從身側(cè)響起搞坝,我...
    開(kāi)封第一講書(shū)人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤搔谴,失蹤者是張志新(化名)和其女友劉穎魁袜,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體敦第,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡峰弹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了芜果。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鞠呈。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖右钾,靈堂內(nèi)的尸體忽然破棺而出蚁吝,到底是詐尸還是另有隱情,我是刑警寧澤舀射,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布窘茁,位于F島的核電站,受9級(jí)特大地震影響脆烟,放射性物質(zhì)發(fā)生泄漏山林。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一邢羔、第九天 我趴在偏房一處隱蔽的房頂上張望驼抹。 院中可真熱鬧,春花似錦拜鹤、人聲如沸框冀。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)左驾。三九已至,卻和暖如春极谊,著一層夾襖步出監(jiān)牢的瞬間诡右,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工轻猖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留帆吻,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓咙边,卻偏偏與公主長(zhǎng)得像猜煮,于是被迫代替她去往敵國(guó)和親次员。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容