Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#1316 from joshiujjawal22/master
Browse files Browse the repository at this point in the history
Adding 3 sum problem, array rotation
  • Loading branch information
deadshotsb authored May 29, 2020
2 parents 88c6ad9 + 3b52109 commit 65dcfd9
Show file tree
Hide file tree
Showing 2 changed files with 135 additions and 0 deletions.
60 changes: 60 additions & 0 deletions Others/3 sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package Others;

import java.util.Scanner;
import java.util.Arrays;

/**
* To find triplet equals to given sum in complexity O(n*log(n))
*
*
* Array must be sorted
*
* @author Ujjawal Joshi
* @date 2020.05.18
*
* Test Cases:
Input:
* 6 //Length of array
12 3 4 1 6 9
target=24
* Output:3 9 12
* Explanation: There is a triplet (12, 3 and 9) present
in the array whose sum is 24.
*
*
*/


class threesum{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
int n=sc.nextInt(); //Length of an array

int a[]=new int[n];

for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Target");
int n_find=sc.nextInt();

Arrays.sort(a); // Sort the array if array is not sorted

for(int i=0;i<n;i++){

int l=i+1,r=n-1;

while(l<r){
if(a[i]+a[l]+a[r]==n_find) {System.out.println(a[i]+" "+ a[l]+" "+a[r]);break;} //if you want all the triplets write l++;r--; insted of break;
else if(a[i]+a[l]+a[r]<n_find) l++;
else r--;
}
}



}
}
75 changes: 75 additions & 0 deletions Others/Rotation of array without using extra space.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package Others;

import java.util.*;

/**
* Rotation of array without using extra space
*
*
* @author Ujjawal Joshi
* @date 2020.05.18
*
* Test Cases:
Input:
2 //Size of matrix
1 2
3 4
Output:
3 1
4 2
------------------------------
Input:
3 //Size of matrix
1 2 3
4 5 6
7 8 9
Output:
7 4 1
8 5 2
9 6 3
*
*/

class main{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[][]=new int[n][n];

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
int temp=0;

// Rotation of array by swapping their values
for(int i=0;i<n/2;i++)
{
for(int j=i;j<n-i-1;j++)
{
temp=a[i][j];
a[i][j]=a[n-j-1][i];
a[n-j-1][i]=a[n-i-1][n-j-1];
a[n-i-1][n-j-1]=a[j][n-i-1];
a[j][n-i-1]=temp;
}
}

// printing of sorted array
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");

}
System.out.println();
}

}


}

0 comments on commit 65dcfd9

Please sign in to comment.