cshreyas
BAN USER/*
* Write a function that would return the 5th element from the
* tail (or end) of a singly linked list of integers, in one pass,
* and then provide a set of test cases against that function
* (please do not use any list manipulation functions that you
* do not implement yourself).
*/
class App {
public static void main(String[] args) {
int arr[] = new int[] { 0, 1, 2, 3, 4, 5, 6 };
int lastLocation = 0;
while (true) {
try {
System.out.println(arr[lastLocation]);
lastLocation = lastLocation + 5;
} catch (ArrayIndexOutOfBoundsException e) {
//System.out.println("arr Out of index: " + lastLocation);
break;
}
}
lastLocation--;
for (int i = 0; i < 5; i++) {
try {
// This sysout statement ensure that same element is not hit
// twice
System.out.println(arr[lastLocation]);
if(lastLocation < 4) {
System.out.println("Array Length less than 5");
break;
}
// System.out.println("Last element of array: "
// + arr[lastLocation]);
System.out.println("5th Last element of array: "
+ arr[lastLocation - 4]);
break;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(lastLocation--);
}
}
}
}
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/*
* Write a program to find the element in an array that is repeated
* more than half number of times. Return -1 if no such element is found.
*/
public class App {
private static boolean findOcc(int[] arr) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
Integer value = map.get(arr[i]);
if (value == null)
value = 1;
else
value++;
map.put(arr[i], value);
}
for (Entry<Integer, Integer> entry : map.entrySet()) {
int value = entry.getValue();
if (value > (arr.length / 2))
return true;
}
return false;
}
public static void main(String[] args) {
int arr[] = { 4, 3, 10, 3, 7, 7, 6, 7, 7, 7, 78, 7, 7 };
System.out.println(Arrays.toString(arr));
System.out.println(findOcc(arr));
}
}
- cshreyas April 17, 2013