162. Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
因為Amaon interview 不收python ,所以開始用 java 刷 leetcode,
這題老毛病又犯了-沒看清楚題意就開始作題
一開始以為這跟algo 作業一樣是rotated ascending order array 找maximum,
結果testcase 跑下去才發現方向錯
不夠謹慎啊......要注意 !!!結果follow 提議後簡單超多,還算快就解了,紀念性的第一題 java
Success:
0ms
class Solution { public int findPeakElement(int[] nums) { if( nums.length == 1 || nums[0] > nums[1]) return 0; if( nums[nums.length-1] > nums[nums.length-2]) return nums.length-1; for(int i=1; i<nums.length-1;i++) if(nums[i] > nums[i+1] && nums[i] > nums[i-1]) return i; return -1; } }
16. 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
概念跟上面一題類似,不過要注意diff 概念,只有在diff 有變小時才更新
Success:
12% 37ms
class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int index =0, record = Integer.MAX_VALUE; while( index < nums.length-2) { int remain = target - nums[index], l=index+1, r=nums.length-1; while(l < r) { int sum = nums[index] + nums[l] + nums[r]; int diff = target - sum; if(record == Integer.MAX_VALUE || Math.abs(diff) < Math.abs(target - record)) record = sum; if (diff < 0) do {r--;} while(nums[r] == nums[r+1] && l < r); else if(diff > 0) do {l++;} while(nums[l] == nums[l-1] && l < r); else break; } index++; while(index < nums.length-2 && nums[index] == nums[index-1]) index++; } return record; } }
留言列表