Skip to content

Commit

Permalink
friupdate14jan1
Browse files Browse the repository at this point in the history
  • Loading branch information
Akshaya-Amar committed Jan 14, 2022
1 parent 0403bf8 commit d27dddb
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 7 deletions.
34 changes: 34 additions & 0 deletions C++/BinarySearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Source: https://leetcode.com/problems/binary-search/
Time: O(log base2 n), where n is the length of the given array(nums)
Space: O(1), in-place
*/

class Solution {
public:
int search(vector<int>& nums, int target) {

int start = 0;
int end = nums.size() - 1;

while(start <= end) {

int mid = start + ((end - start) >> 1);

if(nums[mid] == target) {
return mid;
}

if(nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}

return -1;
}
};
16 changes: 9 additions & 7 deletions Java/AddBinary.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
Source: https://leetcode.com/problems/add-binary/
Time Comlexity : O(Max(m, n)), where m and n are the length of given Strings a and b respectively.
Space Complexity : O(Max(m, n)), as we need a StringBuilder whose size is equal to max of length of 2 input strings
Time Comlexity : O(max(m, n)), where m and n are the lengths of given Strings a and b respectively.
Space Complexity : O(max(m, n)), as we need a StringBuilder whose size is equal to max of length of 2 input strings
*/

Expand All @@ -12,27 +12,29 @@ public String addBinary(String a, String b) {

int aLen = a.length() - 1;
int bLen = b.length() - 1;
StringBuilder res = new StringBuilder(Math.max(aLen, bLen) + 2);
int maxLen = Math.max(aLen, bLen) + 2;
char[] res = new char[maxLen];
int sum = 0;

while(aLen >= 0 || bLen >= 0) {

if(aLen >= 0 && a.charAt(aLen--) == '1') {
if(aLen >= 0 && a.charAt(aLen--) == '1') {
sum += 1;
}

if(bLen >= 0 && b.charAt(bLen--) == '1') {
sum += 1;
}

res.append(sum & 1);
res[--maxLen] = (char)((sum & 1) + 48);
sum >>= 1;
}

if(sum != 0) {
res.append(1);
res[0] = '1';
return String.valueOf(res);
}

return res.reverse().toString();
return String.valueOf(res, 1, res.length - 1);
}
}
33 changes: 33 additions & 0 deletions Java/BinarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
Source: https://leetcode.com/problems/binary-search/
Time: O(log base2 n), where n is the length of the given array(nums)
Space: O(1), in-place
*/

class Solution {
public int search(int[] nums, int target) {

int start = 0;
int end = nums.length - 1;

while(start <= end) {

int mid = start + (end - start ) >> 1;

if(nums[mid] == target) {
return mid;
}

if(nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}

return -1;
}
}

0 comments on commit d27dddb

Please sign in to comment.