Leet Code [Array]
2 min readJan 8, 2024
Question
1. Two Sum
Given an array of integers nums and an integer target, return
indices of the two numbers such that they add up to target.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
# Method 1 (Brute Force Approach)
class Solution {
public int[] twoSum(int[] nums, int target) {
int i ,j;
int a[] = new int[2];
int n= nums.length;
int sum =0;
for (i=0;i<n;i++){
for (j=i+1;j<n;j++){
sum=nums[i]+nums[j];
if(target==sum){
a[0]=i;
a[1]=j;
}}
}
return a;
}
}
complex city o(n2)
=========Method 2 =========
Using HashMap o(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] a = new int[2];
HashMap<Integer,Integer> map = new HashMap<>();
for (int i=0;i<nums.length;i++){
int value = target - nums[i];
if(map.containsKey(value)){
a[0] = i;
a[1] = map.get(value);
}
map.put(nums[i],i);
}
return a;
}
}
26(Leetcode). Remove Duplicates from Sorted Array
Given an integer array nums sorted in non-decreasing order,
remove the duplicates in-place such that each unique element appears only once.
The relative order of the elements should be kept the same.
Then return the number of unique elements in nums.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
## Wrong approch
class Solution {
public int removeDuplicates(int[] nums) {
Set<Integer> set = new HashSet();
for(int i=0;i<nums.length;i++){
set.add(nums[i]);
}
return set.size();
}
}
Method 1
class Solution {
public int removeDuplicates(int[] nums) {
int j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=nums[j]){
j++;
nums[j]=nums[i];
}
}
return j+1;
}
}
Given an integer array nums and an integer val,
remove all occurrences of val in nums in-place.
The order of the elements may be changed.
Then return the number of elements in nums which are not equal to val.
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
class Solution {
public int removeElement(int[] nums, int val) {
int j,count=0;
for(j=0;j<nums.length;j++){
if(nums[j] !=val){
nums[count] =nums[j];
count++;
}
}
return count;
}
}
You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].