Code For NonGeek
Would you like to react to this message? Create an account in a few clicks or log in to continue.

you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence

Go down

you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence Empty you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence

Post  Admin Wed Nov 09, 2011 7:40 pm

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;
}
}

Admin
Admin

Posts : 131
Join date : 2011-08-16

https://codefornongeek.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum