1. 程式人生 > >將陣列中指定的數字刪除

將陣列中指定的數字刪除

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;
	}