- Find the minimum distance between two numbers in an array
public class MinimumDistanceBetween {
public int getDistanceBetween(int[] arr, int first, int second) {
int minDis = Integer.MAX_VALUE;
int j = 0;
int temp = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == first || arr[i] == second) {
temp = arr[i];
j = i;
break;
}
}
for (int i = j; i < arr.length; i++) {
if (arr[i] == first || arr[i] == second) {
if (arr[i] != temp) {
if (minDis > i - j){
minDis = i - j;
}
j = i;
}
}
}
return minDis;
}
public static void main(String args[]) {
int[] arr = {2, 5, 3, 5, 4, 4, 2, 3};
System.out.println(" Min distance is " + new MinimumDistanceBetween().getDistanceBetween(arr, 3, 2));
}
}
- Convert the Arrays so as the following pattern as defined in comments is observed
/** | |
* Convert an unsorted array into an array such that | |
* a < b > c < d > e < f and so on | |
*/ | |
import java.util.Arrays;
public class DecreaseIncreaseArray {
private static void getOrderChanged(int[] arr) {
int n = arr.length - 1;
int temp = 0;
Arrays.sort(arr);
for (int i = 1; i < n; i += 2) {
if (i + 1 < n) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void main(String args[]) {
int[] arr = { 0, 6, 9, 13, 10, -1, 8, 2, 4, 14, -5 };
getOrderChanged(arr);
}
}
Steps:
1. Sort the array : O(nlogn)
2.compare the element: O(n)
total time complexity : O(nlogn + n)
- Find the number repeating maximum number of time in an array of size length and range of the number is defined by range wherein length <= range
class MaxRepeating {
public int maxRepeating(int[] arr, int length, int range) {
for (int i = 0; i < length; i++) {
arr[arr[i] % range] += range; // as arr[i] will always be <= range so will always have the value for the index falling within the range
}
int max = arr[0];
int result = 0;
for (int i = 1; i < length; i++) {
if (arr[i] > max) {
max = arr[i];
result = i;
}
}
return result;
}
public static void main(String[] args) {
int arr[] = { 2, 3, 3, 5, 3, 4, 1, 7, 4, 4, 4, 4, 4 };
int n = arr.length - 1;
int k = 8;
System.out.println("Maximum repeating element is: "
+ new MaxRepeating().maxRepeating(arr, n, k));
}
}
No comments:
Post a Comment