將陣列中指定的數字刪除
阿新 • • 發佈:2019-02-04
public static void main(String[] args) { int nums[] = {3,2,2,3}; int val = 3; System.out.println(removeElement(nums,val)); } public static int removeElement(int[] nums, int val) { int length = nums.length; int i = 0; while(i<nums.length){ if(val == nums[i]){ --length; //把當前元素放到最後 nums[i] = nums[nums.length-1]; nums = Arrays.copyOf(nums, length); i=0; }else{ ++i; } } System.out.println(Arrays.toString(nums)); return length; }