Eg. {45,50,47,46,49,48}
is a sequence 45, 46,47,48,49,50
answer:
1) find min and max
2) set the min value at position 0, max to the last, others follow the pattern
3) check if there is a[i]==a[a[i]-min], if exists, then not
- import java.util.Arrays;
- public class SequenceIdentify {
- public static void switchElement(int[] input, int x, int y) {
- int z = input[x];
- input[x] = input[y];
- input[y] = z;
- }
- public static boolean identify(int[] a) {
- int size = a.length;
- if (size == 0)
- return false;
- int max = a[0];
- int min = a[0];
- // search the min and max elements
- for (int i = 0; i < a.length; i++) {
- if (a[i] > max) {
- max = a[i];
- }
- if (a[i] < min) {
- min = a[i];
- }
- }
- //check if the count of array is correct
- if(size!=max-min+1)
- return false;
- for (int i = 0; i < size; ) {
- if(a[i]==min+i) {
- //the element is in placed already
- i++;
- } else {
- if(a[i]==a[a[i]-min]){
- //the element is duplicated
- return false;
- } else {
- switchElement(a, i, a[i]-min);
- }
- }
- }
- return true;
- }
- public static void main(String[] args) {
- int[] input = {45,50,47,46,49,48};
- System.out.println("Is sequence: " + identify(input));
- }
- }