Skip to content

Commit 9d2a4e2

Browse files
author
Prashant Jain
committed
Added bit-manipulation and two-pointer
1 parent a0e08d1 commit 9d2a4e2

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package in.knowledgegate.dsa.bitmanipulation;
2+
3+
/**
4+
* Given a non-empty array of integers nums,
5+
* every element appears twice except for one.
6+
* Find that single one.
7+
*
8+
* You must implement a solution with a linear
9+
* runtime complexity and use only constant extra
10+
* space.
11+
*
12+
* Example 1:
13+
* Input: nums = [2,2,1]
14+
* Output: 1
15+
*
16+
* Example 2:
17+
* Input: nums = [4,1,2,1,2]
18+
* Output: 4
19+
*
20+
* Example 3:
21+
* Input: nums = [1]
22+
* Output: 1
23+
*
24+
* Constraints:
25+
* 1 <= nums.length <= 3 * 104
26+
* -3 * 104 <= nums[i] <= 3 * 104
27+
* Each element in the array appears twice except
28+
* for one element which appears only once.
29+
*/
30+
public class SingleNumber {
31+
public int singleNumber(int[] nums) {
32+
int num = 0;
33+
for (int i = 0; i < nums.length; i++) {
34+
num ^= nums[i];
35+
}
36+
return num;
37+
}
38+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package in.knowledgegate.dsa.twopointer;
2+
3+
/**
4+
* Given an integer array nums and an integer val,
5+
* remove all occurrences of val in nums in-place.
6+
* The relative order of the elements may be changed.
7+
*
8+
*
9+
* Do not allocate extra space for another array.
10+
* You must do this by modifying the input array
11+
* in-place with O(1) extra memory.
12+
*
13+
*
14+
* Example 1:
15+
* Input: nums = [3,2,2,3], val = 3
16+
* Output: 2, nums = [2,2,_,_]
17+
* Explanation: Your function should return k = 2,
18+
* with the first two elements of nums being 2.
19+
* It does not matter what you leave beyond the
20+
* returned k (hence they are underscores).
21+
*
22+
* Example 2:
23+
* Input: nums = [0,1,2,2,3,0,4,2], val = 2
24+
* Output: 5, nums = [0,1,4,0,3,_,_,_]
25+
* Explanation: Your function should return k = 5,
26+
* with the first five elements of nums containing
27+
* 0, 0, 1, 3, and 4.
28+
*/
29+
public class RemoveElement {
30+
public int removeElement(int[] nums, int val) {
31+
int insertLoc = 0;
32+
for (int i = 0; i < nums.length; i++) {
33+
if (val != nums[i]) {
34+
nums[insertLoc++] = nums[i];
35+
}
36+
}
37+
return insertLoc;
38+
}
39+
}

0 commit comments

Comments
 (0)