dklol
BAN USERimport java.util.*;
/*
Find max element and min element, max-min / (len-1) = common difference
find min element, insert all min,min+cd,..,max in hashset
traverse array and see if all in hashset
if yes, sequence
else no
Time and Space Complexity : Both O(n)
*/
class isArithSequence
{
public static void main(String args[]) {
HashSet s = new HashSet();
int a[] = {0,15,75,45,30,60};
int min = a[0],max =a[0];
boolean flag = true;
for(int i=1;i<a.length;i++) {
if(a[i]>max) {
max = a[i];
}
if(a[i]<min) {
min = a[i];
}
}
int cD = (max-min)/(a.length-1);
for(int i=min;i<=max;i=i+cD) {
s.add(i);
}
for(int i=0;i<a.length;i++) {
if(!s.contains(a[i])) {
flag = false;
break;
}
}
System.out.println("Is Arithmetic sequence : "+flag);
}
}
class BinarySearch {
public static void main(String args[]) {
int x[]= {0,1,2,3,4,5,6,7,8};
for(int i=0;i<=13;i++) {
System.out.println("Position of "+i+" : "+BS(x,0,x.length-1,i)+".");
}
}
public static int BS(int x[],int low,int high,int key) {
if(high<low) {
return -1;
}
else {
int mid = low + (high-low)/2;
if(x[mid]==key) {
return mid;
}
else if(key>x[mid]) {
return BS(x,mid+1,high,key);
}
else {
return BS(x,low,mid-1,key);
}
}
}
}
import java.util.*;
class Node {
int val;
Node left,right,random;
Node(int x) {
val = x;
}
}
class InorderStorePath {
public static void main(String args[]) {
Node x = new Node(4);
x.left = new Node(2);
x.right = new Node(6);
x.left.left = new Node(1);
x.left.right = new Node(3);
x.right.left = new Node(5);
x.right.right = new Node(7);
inorderConstruct(x);
while(x.left!=null) {
x = x.left;
}
while(x!=null) {
System.out.print(x.val+" ");
x = x.random;
}
}
public static void inorderConstruct(Node root) {
Stack<Node> s = new Stack<Node>();
Node current = root;
Node prev = null;
while(true) {
if(current!=null) {
s.push(current);
current = current.left;
}
else if(!s.isEmpty()) {
current = s.pop();
if(prev!=null) {
prev.random = current;
}
prev = current;
current = current.right;
}
else {
break;
}
}
}
}
- dklol March 01, 2016