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 Word SearchLeetCode
- leetcode–57–Insert IntervalLeetCode
- LeetCode之Insert Interval(Kotlin)LeetCodeKotlin
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- [LeetCode] 212. Word Search IILeetCode
- 【leetcode】P35SearchInsertPositionLeetCode
- LeetCode 98. Validate Binary Search TreeLeetCode
- LeetCode之Increasing Order Search Tree(Kotlin)LeetCodeKotlin
- [LeetCode] 57. Insert Interval 插入區間LeetCode
- [LeetCode] 380. Insert Delete GetRandom O(1)LeetCodedeleterandom
- ES(Elastic Search)update操作設定無 docment時進行insertAST
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- [LeetCode] 501. Find Mode in Binary Search TreeLeetCode
- [LeetCode] 702. Search in a Sorted Array of Unknown SizeLeetCode
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- LeetCode 501. Find Mode in Binary Search TreeLeetCode
- LeetCode 1305 All Elements in Two Binary Search TreesLeetCode
- [LeetCode] 109. Convert Sorted List to Binary Search TreeLeetCode
- Java for LeetCode 109 Convert Sorted List to Binary Search TreeJavaLeetCode
- Java實現 LeetCode 35 搜尋插入位置JavaLeetCode
- Oracle中的insert/insert all/insert firstOracle
- LeetCode每日一題: 搜尋插入位置(No.35)LeetCode每日一題
- Q2 LeetCode35 搜尋插入位置LeetCode
- leetcode【210】【Depth-first Search】Course Schedule II【c++版本】LeetCodeC++
- LeetCode C++ 441. Arranging Coins【Math/Binary Search】簡單LeetCodeC++
- position
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- CSS position:sticky與position:fixed 區別CSS
- Position定位
- css positionCSS
- insert into select
- position和BFC
- CSS之positionCSS
- 解析position: sticky;
- position和float
- insert all和insert first語句的用法