35-搜索插入位置

给定排序数组和目标值,如果找到目标,则返回索引。如果没有,请返回索引按顺序插入的索引。
您可以假设数组中没有重复项。
例1:
输入: [1,3,5,6],5
输出: 2
例2:
输入: [1,3,5,6],2
输出: 1

 

解法:
 public int searchInsert(int[] nums, int target) {
            int m=0;
            for (int i=0;i<nums.length;i++)
            {
                if (target>nums[nums.length-1])
                {
                    m=nums.length;break;
                }
                if (target>nums[i])
                    m++;
            }
            return m;
        }

 

posted @ 2019-04-20 21:14  Dloading  阅读(99)  评论(0编辑  收藏  举报