[LeetCode 35] Search Insert Position Solution

来源:互联网 发布:淘宝有哪几种营销方式 编辑:程序博客网 时间:2024/05/18 22:11

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

Idea: check the special case is very important in this problem. Like if the target is at the first location, last location

class Solution {public:    int searchInsert(int A[], int n, int target) {                if(n <= 0) return n;        int flag = 0;        for(int i = 0; i < n; i++){            if(A[i] == target)                 return i;            else if(A[i] < target) {                if(i == n - 1) return n;                flag = 1;                }            else if(A[i] > target){                if(i == 0) return 0;                else if(flag == 1) return i ;            }        }    }};



0 0
原创粉丝点击