【leetcode】P35SearchInsertPosition
//給定一個排序陣列和一個目標值,在陣列中找到目標值,並返回其索引。如果目標值不存在於陣列中,返回它將會被按順序插入的位置。
//
// 你可以假設陣列中無重複元素。
//
// 示例 1:
//
// 輸入: [1,3,5,6], 5
//輸出: 2
//
//
// 示例 2:
//
// 輸入: [1,3,5,6], 2
//輸出: 1
//
//
// 示例 3:
//
// 輸入: [1,3,5,6], 7
//輸出: 4
//
//
// 示例 4:
//
// 輸入: [1,3,5,6], 0
//輸出: 0
//
// Related Topics 陣列 二分查詢
// ? 724 ? 0
package leetcode.editor.cn;
//Java:搜尋插入位置
public class P35SearchInsertPosition {
public static void main(String[] args) {
Solution solution = new P35SearchInsertPosition().new Solution();
// TO TEST
int i = solution.searchInsert(new int[]{1, 3, 5, 6}, 2);
System.out.println(i);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int searchInsert(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
r = mid - 1;
else l = mid + 1;
}
return l ;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
相關文章
- 【LeetCode】如何學習LeetCode?LeetCode
- leetcodeLeetCode
- LeetCode in actionLeetCode
- leetcode 238LeetCode
- LeetCode 164 最大間距 HERODING的LeetCode之路LeetCode
- LeetCode 143 重排連結串列 HERODING的LeetCode之路LeetCode
- LeetCode問題LeetCode
- 【LeetCode】Jewels and StonesLeetCode
- Leetcode 513 javascriptLeetCodeJavaScript
- LeetCode 162 JavascriptLeetCodeJavaScript
- Leetcode 921 JavascriptLeetCodeJavaScript
- [Leetcode] Edit DistanceLeetCode
- LeetCode 克隆圖LeetCode
- LeetCode #378 JavaScriptLeetCodeJavaScript
- LeetCode 747 JavaScriptLeetCodeJavaScript
- Leetcode725LeetCode
- LeetCode 53 JSLeetCodeJS
- LeetCode 50 JSLeetCodeJS
- Leetcode03LeetCode
- LeetCode 799 JavaScriptLeetCodeJavaScript
- leetcode690LeetCode
- [LeetCode] Group AnagramLeetCode
- [LeetCode] Rotate StringLeetCode
- LeetCode 283 jsLeetCodeJS
- Leetcode #463 JavascriptLeetCodeJavaScript
- Leetcode # 495 JavascriptLeetCodeJavaScript
- Leetcode 229 JavaScriptLeetCodeJavaScript
- golang刷leetcodeGolangLeetCode
- Leetcode目錄LeetCode
- LeetCode:快速排序LeetCode排序
- leetcode Sum系列LeetCode
- LeetCode三則LeetCode
- LeetCode2:LeetCode
- The best LeetCode NodesLeetCode
- LeetCode兩則LeetCode
- Leetcode學習LeetCode
- leetcode no.1LeetCode
- leetcode開篇LeetCode