一个数组,每隔两个数删除一个数,到数组末尾接着从头开始,一直循坏,得出最后删除的一个元素的下标...

  1. public class DeleteEveryTwo {  
  2.     public static void main(String[] args) {  
  3.         int index = getLastDeletedIndex(8);  
  4.         System.out.println("The last index deleted is " + index);  
  5.     }  
  6.   
  7.     /** 
  8.      *  
  9.      * @param a 
  10.      *            数组长度 
  11.      * @return 最后被删除的数的原始下标 
  12.      */  
  13.     public static int getLastDeletedIndex(int len) {  
  14.         if (len <= 0) { // 如果数组长度不满足要求则返回 -1  
  15.             return -1;  
  16.         }  
  17.   
  18.         int[] arr = new int[len];  
  19.         for (int i = 0; i < len; i++) { // 初始化每个元素的值为当前下标  
  20.             arr[i] = len;  
  21.         }  
  22.   
  23.         final int DELFLAG = len + 1; // 删除标志位  
  24.         int currentSize = len; // 记录数组当前有效长度(即未被置为删除标志的元素个数),最后变为 0  
  25.         final int STEP = 2; // 步长  
  26.         int count = 0; // 步长计数  
  27.         int lastDelIndex = 0; // 记录最后被删除的元素的下标  
  28.         int i = 0; // 循环下标  
  29.   
  30.         while (currentSize != 0) {  
  31.             if (arr[i] != DELFLAG) { // 判读当前元素是否等于删除标志  
  32.                 if (count++ == STEP) { // 当步长计数满足步长则  
  33.                     arr[i] = DELFLAG; // 将元素置为删除标志位  
  34.                     lastDelIndex = i; // 记录该处下标  
  35.                     currentSize--; // 有效数组长度减 1  
  36.                     count = 0; // 步长计数归零  
  37.                     System.out.println("Deleted index is " + i % len);  
  38.                 }  
  39.             }  
  40.             i = (i + 1) % len; // 下标取余实现循环下标  
  41.         }  
  42.         return lastDelIndex;  
  43.     }  
  44. }  

转载于:https://www.cnblogs.com/GodZhe/p/5414809.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值