package javaLeetCode.primary;
public class SearchInsertPosition_35 {
public static void main(String[] args) {
int []nums = {1,3,5,6};
System.out.println(searchInsert_2(nums, 0));
}//end main()
/**
* Conventional idea.
* sequential search.
* */
/*
* Test Data:
* Input: [1,3,5,6], 5
* Output: 2
*
*Input: [1,3,5,6], 2
* Output: 1
*
*Input: [1,3,5,6], 7
* Output: 4
*
*Input: [1,3,5,6], 0
* Output: 0
* */
public static int searchInsert_1(int[] nums, int target) {
for(int i =0;i<nums.length;i++) {
if(nums[i]==target) {
return i;
}else {
continue;
}//end if
}//end for
for(int i=0;i<nums.length;i++) {
if(target>nums[i]) {
continue;
}else {
return i;
}//end if
}//end for
return nums.length;
}//end searchInsert()
/**
* Conventional idea.
* binary search.
* */
public static int searchInsert_2(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
int mid = -1;
int returnInt = -1;
//Search the array "nums" for the "target" target.
while(low<=high) {
mid = (low+high)/2;
if(target==nums[mid]) {
returnInt = mid;
return returnInt;
}else if(target<nums[mid]) {
high = mid - 1;
}else if(target>nums[mid]) {
low = mid +1;
}//end if
}//end while
//Find insert position.
if(low>high) {
for(int i=0;i<nums.length;i++) {
if(target>nums[i]) {
continue;
}else {
returnInt = i;
return returnInt;
}//end if
}//end for
}//end if
return nums.length;
}//end searchInsert()
}//end SearchInsertPosition_35
Java实现LeetCode_0035_SearchInsertPosition
2023-09-14 08:58:08 时间
相关文章
- Java实现 LeetCode 822 翻转卡片游戏(暴力)
- Java实现 LeetCode 801 使序列递增的最小交换次数 (DP)
- Java实现 LeetCode 792 自定义字符串排序(暴力)
- Java实现 LeetCode 765 情侣牵手(并查集 || 暴力)
- Java实现 LeetCode 754 到达终点数字(暴力+反向)
- Java实现 蓝桥杯 算法训练 Cowboys
- Java实现 LeetCode 731 我的日程安排表 II(二叉树)
- Java实现 LeetCode 720 词典中最长的单词(字典树)
- Java实现 LeetCode 面试题13. 机器人的运动范围(DFS)
- Java实现 LeetCode 707 设计链表(环形链表)
- Java实现 LeetCode 587 安装栅栏(图算法转换成数学问题)
- Java实现 LeetCode 564 寻找最近的回文数(今天要GG在这道题了 头晕+题难(((φ(◎ロ◎;)φ))))...
- Java实现 LeetCode 554 砖墙(缝隙可以放在数组?)
- Java实现 LeetCode 524 通过删除字母匹配到字典里最长单词(又是一道语文题)
- Java实现 LeetCode 507 完美数
- Java实现 LeetCode 493 翻转对
- Java实现 LeetCode 474 一和零
- Java实现 LeetCode 402 移掉K位数字
- Java实现 LeetCode 381 O(1) 时间插入、删除和获取随机元素 - 允许重复
- Java实现 LeetCode 367 有效的完全平方数
- Java实现 LeetCode 336 回文对
- Java实现 LeetCode 327 区间和的个数
- Java实现 LeetCode 239 滑动窗口最大值
- Java实现 LeetCode 238 除自身以外数组的乘积
- Java实现 LeetCode 214 最短回文串
- Java实现 LeetCode 147 对链表进行插入排序
- Java实现 LeetCode 55 跳跃游戏
- Java实现LeetCode_0012_IntegerToRoman
- Java实现 Leetcode 88 合并两个有序数组
- 【JAVA】 02-Java对象细节