題目要求:在一個有序的數組中,找到一個目標值,返回該值得下標。若沒有找到該值,則返回該值順序插入的下標
例如,
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0面試
public int searchInsert(int[] nums, int target) { int index=0; for( ; index<nums.length ; index++){ if(nums[index]>=target){ break; } } return index; }
使用雙指針後效率比單指針效率高數組
public int searchInsert2(int[] nums, int target) { int pointerLeft = 0; int pointerRight = nums.length-1; for( ; pointerLeft<=pointerRight ; pointerLeft++, pointerRight--){ if(nums[pointerLeft]>=target){ return pointerLeft; } if(nums[pointerRight]<target){ return pointerRight+1; } } return pointerLeft; }
使用二分法也能夠,可是二分法可能會在數組有重複數字狀況下產生多個答案微信
public int searchInsert3(int[] nums, int target) { int pointerLeft = 0; int pointerRight = nums.length-1; while(pointerLeft<=pointerRight){ int mid = (pointerLeft+pointerRight)/2; if(nums[mid]==target){ return mid; }else if(nums[mid]>target){ pointerRight = mid-1; }else{ pointerLeft = mid+1; } } return pointerLeft; }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa