iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 29
0

題目:

https://leetcode.com/problems/find-peak-element/
回傳陣列中比左邊數字和右邊數字大之索引值。

解題思路:

先用for迴圈找出正常情況下比左邊和右邊大之索引值並回傳,需設想當條件不在此內需在設條件另外判斷並回傳。

C版本:

int left = 0, right = numsSize - 1;
while (left < right) {
  int mid = left + (right - left) / 2;
  if (nums[mid] < nums[mid + 1]) 
    left = mid + 1;
  else 
    right = mid;
}
return right;

Javascript版本:

var findPeakElement = function(nums) {
    var len=nums.length;
    if(len == 1)
        return 0;
    for(var i=1;i<len-1;i++){
        if(nums[i]>nums[i+1]&&nums[i]>nums[i-1]){
            return i;
        }
    }
    if(nums[0]>nums[1]) return 0;
    if(nums[len-1]>nums[len-2]) return len-1;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

If you keep on believing, the dream that you wish will come true.
如果你堅持你的信念,美夢總有一天會成真


上一篇
DAY28 Invert Binary Tree
下一篇
DAY30 Find Minimum in Rotated Sorted Array II
系列文
刷題記錄與人生分享34

尚未有邦友留言

立即登入留言