leetcode_35_SearchInsertPosition

題目描述: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.給定一個排序好的數組和一個目標,找出目標在數組中的位置或者他應該在的位置數組

這道題目很簡單。
能夠採用二分查找法。code

int low = 0;
        int high = nums.length-1;
        
        while(low <= high){
            int mid = (low+high)/2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){
                high = mid -1;
            }else{
                low = mid +1;
            }
            
        }
        return low;
本站公眾號
   歡迎關注本站公眾號,獲取更多信息