?LeetCode刷題實戰(zhàn)35: 搜索插入位置
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎知識和業(yè)務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?搜索插入位置,我們先來看題面:
https://leetcode-cn.com/problems/search-insert-position/
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array.
題意
樣例
示例 1:
輸入: [1,3,5,6], 5
輸出: 2
示例?2:
輸入: [1,3,5,6], 2
輸出: 1
示例 3:
輸入: [1,3,5,6], 7
輸出: 4
示例 4:
輸入: [1,3,5,6], 0
輸出: 0
題解
public?int?searchInsert(int[] nums, int?target)?{
????????if?(nums.length == 0) {
????????????return?0;
????????}
????????for?(int?i = 0; i < nums.length; i++) {
????????????if?(nums[i] >= target)
????????????????return?i;
????????}
????????return?nums.length;
????}
class?Solution?{
????public?int?searchInsert(int[] nums, int?target)?{
????????int?n = nums.length;
????????int?left = 0, right = n - 1, ans = n;
????????while?(left <= right) {
????????????int?mid = ((right - left) >> 1) + left;
????????????if?(target <= nums[mid]) {
????????????????ans = mid;
????????????????right = mid - 1;
????????????} else?{
????????????????left = mid + 1;
????????????}
????????}
????????return?ans;
????}
}
上期推文:
