you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence
Page 1 of 1
you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence
a = {4,5,1,5,7,4,3,6,3,1,9}
max subarray = {5,7,4,3,6}
public class LongestRange {
public int[] longest(int[] a) {
int start = 0;
int maxLen = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0; i<a.length; i++) {
int left = map.containsKey(a[i]-1)? map.get(a[i]-1) : 0;
int right = map.containsKey(a[i]+1)? map.get(a[i]+1) : 0;
int len = left + 1 + right;
map.put(a[i]-left, len);
map.put(a[i]+right, len);
if (len > maxLen) {
maxLen = len;
start = a[i] - left;
}
}
int[] b = new int[maxLen];
for (int i=0; i<maxLen; i++) b[i] = start + i;
return b;
}
}
max subarray = {5,7,4,3,6}
public class LongestRange {
public int[] longest(int[] a) {
int start = 0;
int maxLen = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0; i<a.length; i++) {
int left = map.containsKey(a[i]-1)? map.get(a[i]-1) : 0;
int right = map.containsKey(a[i]+1)? map.get(a[i]+1) : 0;
int len = left + 1 + right;
map.put(a[i]-left, len);
map.put(a[i]+right, len);
if (len > maxLen) {
maxLen = len;
start = a[i] - left;
}
}
int[] b = new int[maxLen];
for (int i=0; i<maxLen; i++) b[i] = start + i;
return b;
}
}
Similar topics
» An array of integers, all appear twice except one, find this number.
» Find a point in an array where sum of left side array members(wrt to that point) and right side(wrt to that point) are equal..in other words equilibrium point.
» In an array there is one element which repeats more than n/2 times...find the number in 0(n) time and 0(1) space
» Find pairs in an array that sum to y
» Find the n-th largest int in an array
» Find a point in an array where sum of left side array members(wrt to that point) and right side(wrt to that point) are equal..in other words equilibrium point.
» In an array there is one element which repeats more than n/2 times...find the number in 0(n) time and 0(1) space
» Find pairs in an array that sum to y
» Find the n-th largest int in an array
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|