【牛客网OJ题】删数

题目描述 :

有一个数组aNJ顺序存放0-N-1,要求每隔两个数删掉一个数,到末尾时循环至开头继续进行,求最后一个被删掉的数·的原始下标位置。以8个数(N=7)为例: {0, 1, 2, 3, 4, 5, 6, 7} , 0->1 >2(删除)->3->4->5(删除)->6->7->0(删除),如此循环直到最后一个数被删除。

输入描述:

每组数据为一行一个整数n(小于等于 1000),为数组成员数,如果大于 1000,则对a[999]进行计算。

输出描述:

一行输出最后一个被删掉的数的原始下标位置

示例:

输入:

8

输出:

6

分析:

有两种方法实现,但是思想都是一样的。说一下用list实现,把从0到n的数放进list集合中,只要list集合中所剩的容量还大于1,那么就还需要继续进行删除。隔两个删就,每次删的都是当前位置的后面第二个,那么就用他当前位置去对list的容量求模,那么我们就可以这样写:(i+2)%size; i==0的时候, 我们移除的就是2号下标,接着需要移除4号下标,那么新的i = (i+2)%size; 

import java.util.*;
 public class Main {
	 public static void main(String[] args) {
		 Scanner sc = new Scanner(System.in);
		 while (sc.hasNext()) {
			 int n = sc.nextInt();
			 if (n > 1000) {
				 n = 999; 
			}
			List<Integer> list = new ArrayList<Integer>();
			for (int i = 0; i < n; i++) {
				list.add(i);
			}
			int i = 0;
			while (list.size() > 1) {
				i = (i + 2) % list.size();
				list.remove(i);
			}
			System.out.println(list.get(0));
		} 
	} 
}
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);      
     while (scanner.hasNextInt()) {
           int len = scanner.nextInt();
           int[] index = new int[len];
          System.out.println(countNum(len, index));
     }
} 
public static int countNum(int len, int[] index) { 
    int i = 0; 
    int count = 0;
    int count1 = 0; 
    while (true) { 
        if (count1 == len) { 
           return i - 1;
        }
       if (i == len) {
            i = i % len;
       }
      if (index[i] != -1) {
           count++; 
      }
     if (count == 3) { 
          count = 0; 
          count1++; 
         index[i % len] = -1; 
        } 
     i++;
    }
  } 
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值