Leetcode 35 Search Insert Position
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
這個題目的意思是找到target在陣列中應該存放的地方,題目較簡單,可以使用暴力或者是二分來做。
1)
class Solution {
public int searchInsert(int[] nums, int target) {
int len = nums.length;
int i = 0;
if(target <= nums[0]){
return 0;
}
for(i = 0 ; i < len ; i++){
if(nums[i] >= target){
return i;
}
}
return len;
}
}
2)
public class Solution {
public int searchInsert(int[] A, int target) {
int left = A.length - 1;
int right = 0;
while(true){
if(A[right] >= target){
return right;
}else if(A[left] < target){
return left + 1;
}
int mid = right + (left - right) / 2;
if(A[mid] <= target){
right++;
}else{
left--;
}
}
}
}
3)
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int i=0;
for(i=0;i<n;i++)
{
if(target <= A[i])
return i;
}
return n;
}
};
相關文章
- LeetCode 35. Search Insert PositionLeetCode
- Leetcode Search Insert PositionLeetCode
- Leetcode-Search Insert PositionLeetCode
- Search Insert Position leetcode javaLeetCodeJava
- Search Insert Position
- [LeetCode] Search Insert Position 搜尋插入位置LeetCode
- 演算法Search Insert Position演算法
- Leetcode Word SearchLeetCode
- Leetcode Search for a RangeLeetCode
- Search Insert Position 查詢給定元素在陣列中的位置,若沒有則返回應該在的位置陣列
- Leetcode-Word SearchLeetCode
- LeetCode 34 Search for a RangeLeetCode
- Leetcode-Search for a rangeLeetCode
- Word Search leetcode javaLeetCodeJava
- Search for a Range leetcode javaLeetCodeJava
- Leetcode Insert IntervalLeetCode
- leetcode34_Search for a RangeLeetCode
- Leetcode Search in Rotated Sorted ArrayLeetCode
- leetcode–57–Insert IntervalLeetCode
- Leetcode-Insert IntervalLeetCode
- Insert Interval leetcode javaLeetCodeJava
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- LeetCode-Add and Search WordLeetCode
- Leetcode Search in Rotated Sorted Array IILeetCode
- Leetcode Search a 2D MatrixLeetCode
- Leetcode Unique Binary Search TreesLeetCode
- Leetcode-Search in Rotated Sorted ArrayLeetCode
- Search in Rotated Sorted Array leetcode javaLeetCodeJava
- 【LeetCode 235_二叉搜尋樹】Lowest Common Ancestor of a Binary Search TreeLeetCode
- [LeetCode] 212. Word Search IILeetCode
- leetcode33_Search in Rotated Sorted ArrayLeetCode
- LeetCode-Search in Rotated Sorted Array IILeetCode
- Leetcode Validate Binary Search TreeLeetCode
- Leetcode-Search a 2D MatrixLeetCode
- Leetcode-Unique Binary Search TreesLeetCode
- leetcode 之 Recover Binary Search TreeLeetCode
- Unique Binary Search Trees leetcode javaLeetCodeJava