[Day12]35. Search Insert Positio

2017-02-11  本文已影响0人  Shira0905

A EASY problem, just for accomplish today's task.
Already late

DESCRIPTION:
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

ANALYSIS:
So easy!

SOLUTION:

   public static int searchInsert(int[] nums, int target) {
        int i=0;
        for(i=0;i<nums.length;){
            if(target>nums[i]){
                i++;
            }else if(target==nums[i]||target<nums[i]){
                return i;
            }
        }
        return i;
    }
上一篇下一篇

猜你喜欢

热点阅读