2 sum
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
HashMap<Integer,Integer> map = new HashMap();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
res[1] = i+1;
res[0] = map.get(target-nums[i]);
return res;
}
map.put(nums[i],i+1);
}
return res;
}
}
3 sum
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList();
for(int i=0;i<nums.length-2;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
int lo=i+1,hi=nums.length-1;
while(lo<hi){
int sum=nums[i]+nums[lo]+nums[hi];
if(sum==0){
res.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
while(lo<hi&&nums[lo]==nums[lo+1])lo++;
while(lo<hi&&nums[hi]==nums[hi-1])hi--;
lo++;
hi--;
}else if(sum<0) lo++;
else hi--;
}
}
return res;
}
4 sum
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList();
if(nums.length<4) return res;
Arrays.sort(nums);
for(int i=0;i<nums.length-3;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.length-2;j++){
if(j>i+1&&nums[j]==nums[j-1]) continue;
int lo=j+1,hi=nums.length-1;
while(lo<hi){
int sum = nums[i]+nums[j]+nums[lo]+nums[hi];
if(sum==target){
res.add(Arrays.asList(nums[i],nums[j],nums[lo],nums[hi]));
while(lo<hi&&nums[lo]==nums[lo+1]) lo++;
while(lo<hi&&nums[hi]==nums[hi-1]) hi--;
lo++;
hi--;
}else if(sum<target) lo++;
else hi--;
}
}
}
return res;
}
3 sum closest
public int threeSumClosest(int[] nums, int target) {
int res = nums[0] + nums[1] + nums[2];
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
int lo=i+1,hi=nums.length-1;
while(lo<hi){
int sum = nums[i]+nums[lo]+nums[hi];
if(sum<target) lo++;
else hi--;
if(Math.abs(sum-target)<Math.abs(res-target)) res = sum;
}
}
return res;
}
set matrix zeroes
public void setZeroes(int[][] matrix) {
boolean fr = false;
boolean fc = false;
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if(matrix[i][j]==0){
if(i==0) fr = true;
if(j==0) fc = true;
matrix[0][j]=0;
matrix[i][0]=0;
}
}
}
for(int i=1;i<matrix.length;i++){
for(int j=1;j<matrix[0].length;j++){
if(matrix[0][j]==0||matrix[i][0]==0){
matrix[i][j]=0;
}
}
}
if(fr){
for(int i=0;i<matrix[0].length;i++){
matrix[0][i] =0;
}
}
if(fc){
for(int j=0;j<matrix.length;j++){
matrix[j][0] =0;
}
}
}
Container With Most Water
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int max = 0;
while(left < right)
{
max = Math.max(max,area(right,left,height));
if(height[left]< height[right])
{
left++;
}else
{
right--;
}
}
return max;
}
private int area(int right,int left,int[] height)
{
return (right - left) * Math.min(height[right],height[left]);
}