Bloomberg LP Interview Question
Country: United States
#include <iostream>
#include <string>
using namespace std;
int retSecondMax(int a[]){
int sectmp = 0, tmp = a[0];
for(int i =1; i<10; i++){
if(tmp<a[i])
{ sectmp = tmp;
tmp = a[i];
}
}
return sectmp;
}
int main(int argc, char *argv[]) {
int a[10] = {3,4,2,1,8,6,7,9,10};
cout<<retSecondMax(a);
}
private int FindSecondLargest(int[] array)
{
int largest = 0;
int secondLargest = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] > largest)
{
secondLargest = largest;
largest = array[i];
}
else if (array[i] < largest && array[i] > secondLargest)
secondLargest = array[i];
}
return secondLargest;
}
private int FindSecondLargest(int[] array)
{
int largest = 0;
int secondLargest = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] > largest)
{
secondLargest = largest;
largest = array[i];
}
else if (array[i] < largest && array[i] > secondLargest)
secondLargest = array[i];
}
return secondLargest;
}
Based upon quick sort algorithm:
Randomized-Select(A[p..r],i) looking for ith o.s.
if p = rreturn A[p]
q <- Randomized-Partition(A,p,r)
k <- q-p+1 the size of the left partition
if i=k then the pivot value is the answer
return A[q]
else if i < k then the answer is in the front
return Randomized-Select(A,p,q-1,i)
else then the answer is in the back half
return Randomized-Select(A,q+1,r,i-k)
T[n] = O(n)
public static void main(String[] args) {
SecondMax secondMax = new SecondMax();
int [] array = {7,4,6,4,7};
int secondMaxValue = secondMax.getSecondMax(array);
System.out.println("The second max number in the array " + secondMaxValue);
}
private int getSecondMax(int [] array){
int max = Integer.MIN_VALUE;
int smax = Integer.MIN_VALUE;
for(int i =0;i<array.length;i++){
if(array[i] >max ){
max= array[i];
}
else if(smax< array[i]&& array[i]<max){
smax = array[i];
}else continue;
}
return smax;
}
}
#include<iostream>
using namespace std;
int find( int *A , int n )
{
int f = A[0] , s = A[0];
for (int i= 0 ;i < n ; i++ )
{
if( A[i] > f )
{
s = f;
f = A[i];
}
}
return s;
}
int main()
{
int Ar[] = {1,2,3,4,6};
cout << find( Ar , 7 );
return 0;
}
- A March 11, 2012