This question requires a straightforward scan.
We can't help but notice there's only two situations:
0. empty array, so go ahead and insert into 0;
1. if you see nums[i] equal to the target, congratulations and return the i! Also, if you see nums[i] larger, go ahead and return the i because it will be inserted into i.
2. If you can't find such a fit in the Rule No.1. Go ahead and append it to the very end of the Array. And that would be nums.length;
So my clever reader now you can go ahead and give it a try yourself.
:)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int searchInsert(int[] nums, int target) { | |
if (nums == null || nums.length < 1) { | |
return 0; | |
} | |
// O(n) traverse | |
for(int i = 0; i < nums.length; i++) { | |
if (target <= nums[i]) { | |
return i; | |
} | |
} | |
return nums.length; | |
} | |
} |
No comments:
Post a Comment