给定一个数组,判断这个数组的元素是否是在一个序列

504 篇文章 0 订阅

转自出处


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

 

[java]  view plain copy
  1. import java.util.Arrays;  
  2.   
  3. public class SequenceIdentify {  
  4.     public static void switchElement(int[] input, int x, int y) {  
  5.         int z = input[x];  
  6.         input[x] = input[y];  
  7.         input[y] = z;  
  8.     }  
  9.   
  10.     public static boolean identify(int[] a) {  
  11.         int size = a.length;  
  12.         if (size == 0)  
  13.             return false;  
  14.         int max = a[0];  
  15.         int min = a[0];  
  16.         // search the min and max elements  
  17.         for (int i = 0; i < a.length; i++) {  
  18.             if (a[i] > max) {  
  19.                 max = a[i];  
  20.             }  
  21.             if (a[i] < min) {  
  22.                 min = a[i];  
  23.             }  
  24.         }  
  25.           
  26.         //check if the count of array is correct  
  27.         if(size!=max-min+1)  
  28.             return false;  
  29.           
  30.         for (int i = 0; i < size; ) {  
  31.             if(a[i]==min+i) {  
  32.                 //the element is in placed already  
  33.                 i++;  
  34.             } else {  
  35.                 if(a[i]==a[a[i]-min]){  
  36.                     //the element is duplicated  
  37.                     return false;  
  38.                 } else {  
  39.                     switchElement(a, i, a[i]-min);  
  40.                 }  
  41.             }  
  42.         }  
  43.         return true;  
  44.     }  
  45.   
  46.     public static void main(String[] args) {  
  47.         int[] input = {45,50,47,46,49,48};  
  48.         System.out.println("Is sequence: " + identify(input));  
  49.     }  
  50. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值