Yuvraj Singh Babrah
BAN USER/*
Question ID: 18078662
Write a code to print the second largest element in a list
Shortest possible complexity.
Time Complexity: Linear -> O(n)
*/
public class sol18078662{
static int length;
static int[] a;
static int first;
static int second;
public static void main(String[] args){
length = args.length;
a = new int[length];
for(int i = 0; i < length; i ++){
a[i] = Integer.parseInt(args[i]);
}
first = a[0];
second = a[1];
for(int i = 2; i < length; i ++){
if(a[i] < second)
continue;
if(a[i] > first){
second = first;
first = a[i];
}
else
second = a[i];
}
System.out.println(second);
}
}
/*
Question ID: 5201559730257920
Give you an array which has n integers,it has both positive and negative integers.
Now you need sort this array in a special way.After that,the negative integers should in the front,and the positive integers should in the back.
Also the relative position should not be changed.
eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.
O(n)time complexity and O(1) space complexity is perfect.
*/
public class sol5201559730257920{
static int length;
static int[] a;
static int start;
static int end;
static int total_n;
public static void sort(){
while(start < total_n){
if(a[start] < 0)
start ++;
else{
a[end] = a[start] + (a[start] = a[end]) - a[end]; // swap;
end ++;
}
}
}
public static void display(){
for(int i = 0; i < length; i ++){
System.out.print(a[i] + " ");
}
}
public static void main(String[] args){
length = args.length;
a = new int[length];
for(int i = 0; i < length; i ++){
a[i] = Integer.parseInt(args[i]);
if(a[i] < 0) // count total negative numbers
total_n ++;
}
end = total_n; // index where positive num starts
sort();
display();
}
}
public class FacebookSort{
static int length;
static int[] a;
static int start;
static int end;
static int temp;
public static void sort(){
temp = start;
while(temp <= end){
if(a[temp] == 1){
a[start] = a[temp] + (a[temp] = a[start]) - a[start];
start ++;
temp ++;
}
else if(a[temp] == 3){
a[end] = a[temp] + (a[temp] = a[end]) - a[end];
end --;
}
else{
temp ++;
}
}
}
public static void display(){
for(int i = 0; i < length; i ++){
System.out.print(a[i] + " ");
}
}
public static void main(String[] args){
length = args.length;
a = new int[length];
end = length - 1;
for(int i = 0; i < length; i ++){
a[i] = Integer.parseInt(args[i]);
}
sort();
display();
}
}
- Yuvraj Singh Babrah August 29, 2013