leetcode第35题,算是比较简单的题目
题目描述:
/** * Test35 : 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 * * @author xuejupo [email protected] create in 2016-1-20 下午4:45:55 */
翻译一下就是,查找给定的数target在有序数组中应该被插入的位置。
代码:
/** * searchInsert: 返回target在有序数组nums中的应插入位置 * @param nums * @param target * @return * int 返回类型 */ public int searchInsert(int[] nums, int target) { if(nums == null || nums.length == 0){ return 0; } int result = 0; while(result < nums.length && target > nums[result] ){ result++; } return result; }
测试代码:
public static void main(String[] args) { // TODO Auto-generated method stub Test35 t = new Test35(); for(int i = 0; i < 10;i++){ System.out.println(t.searchInsert(new int[]{1,3,5,6}, i) + "\t"+ i); } }
结果:
0 0 0 1 1 2 1 3 2 4 2 5 3 6 4 7 4 8 4 9
时间复杂度为:O(n),空间复杂度为O(1)