【力扣LeetCode】35 搜索插入位置

題目描述(難度易)

給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。

你可以假設數組中無重複元素。

示例 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

鏈接

https://leetcode-cn.com/problems/search-insert-position/

代碼

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int ans = 0;
        bool flag = true;
        for(int i = 0; i < nums.size(); i++){
        	if(nums[i] >= target){
        		ans = i;
        		flag = false;
        		break;
        	}
        }
        if(flag){
            ans = nums.size();
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章