-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #52 from sarthakw7/sarth
Q35_Search_Insert_Position Solution added in java
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
leetCode Solutions/Q35_Search_Insert_Position/Q35_Search_Insert_Position.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
|
||
|
||
// We'll first apply the binary search algorithm on the given sorted array. | ||
// If the target value is found, we'll return that index. | ||
// If not, we'll process until our search space becomes empty. At this point, the index at which the element should be inserted is already saved while we dive our search space by half. | ||
|
||
|
||
|
||
class Solution { | ||
public int searchInsert(int[] nums, int target) { | ||
|
||
int s = 0; | ||
int e = nums.length -1; | ||
|
||
while(s<=e){ | ||
int m = (s+e)>>1; | ||
if(target == nums[m]){ | ||
return m; | ||
} | ||
if(target<nums[m]){ | ||
e = m-1; | ||
}else{ | ||
s = m + 1; | ||
} | ||
} | ||
|
||
return s; | ||
} | ||
} |