描述
示例
算法思路1
不断移动数组将元素删去(并未彻底删除,而是将数字元素前移实现“伪删除”)这样删除元素的位置就呈现一定规律,详细见下图(潦草的画)
答案1
import java.util.*;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入一个整数数组,格式为[1,2,3,4,5,6,7,8,9]:");String input = scanner.nextLine();//去除首尾【】,然后以,将字符串分割String [] tokens = input.substring(1,input.length()-1).split(",");//创建整数数组int [] nums = new int[tokens.length];for (int i = 0; i < tokens.length; i++) {nums[i] =Integer.parseInt(tokens[i]) ;//把字符串转换为整数放入nums[]数组中}int jump = scanner.nextInt();int left = scanner.nextInt();System.out.println(sumOfLeft(nums,jump,left));}private static int sumOfLeft(int[] nums, int jump, int left) {int sum = 0;int i=1;int length=nums.length;//记录不断变化的数组长度if(left+jump>length||jump>=length-1) return -1;//剩余数量和跳数和>数组长度则无需跳while(length>left){//nums中剩余个数>left继续跳i=(i+jump)%length;for( int j=i;j<length-1;j++){nums[j]=nums[j+1];}length--;}sum=nums[0]+nums[1]+nums[2];return sum;}
}
详解1
请忽略我这潦草的字体,懒得不想重画了。
算法思路2
先求整体数组的和,然后不断把删去的元素减去。
答案2
import java.util.*;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入一个整数数组,格式为[1,2,3,4,5,6,7,8,9]:");String input = scanner.nextLine();//去除首尾【】,然后以,将字符串分割String [] tokens = input.substring(1,input.length()-1).split(",");//创建整数数组int [] nums = new int[tokens.length];for (int i = 0; i < tokens.length; i++) {nums[i] =Integer.parseInt(tokens[i]) ;//把字符串转换为整数放入nums[]数组中}int jump = scanner.nextInt();int left = scanner.nextInt();System.out.println(sumOfLeft(nums,jump,left));
// int [] num={1,2,3,4,5,6,7,8,9};
// System.out.println(sumOfLeft(num,4,3));}private static int sumOfLeft(int[] nums, int jump, int left) {int sum = 0;int length=nums.length;//记录不断变化的数组长度if(left+jump>length||jump>=length-1) return -1;//剩余数量和跳数和>数组长度则无需跳ArrayList<Integer> numbers = new ArrayList<>();for(int num:nums){sum +=num;numbers.add(num);}for(int i=(1+jump)%numbers.size();numbers.size()>left;i=(i+jump)%numbers.size()){sum -= numbers.get(i);numbers.remove(i);}return sum;}
}
详解2
使用ArrayList集合类实现真正的删除操作。ArrayList详细操作请移步
Java“集合框架”知识速成笔记学完就去实战(三)-CSDN博客