计蒜客 挑战难题 元素移除

给定一个数组和一个数(该数不一定在数组中),从数组里删掉这个数字,返回剩下的数组长度。

如:A[] = {1, 2, 3, 4, 5}, 要删除数字3, 那么返回数组长度为4.

亲爱的小伙伴们,题目是不是很简单呢?

提示: int removeElement(int A[], int n, int elem)

其中,n代表数组长度,elem代表要删掉的元素。

格式:

输入一个数n,继而输入一个数组A[n],接着输入要删除的元素elem,返回剩余数组长度index.

===============================================================

 1 import java.util.Scanner;
 2 
 3 public class Main 
 4 {
 5     public static void main(String[] args)   
 6     {
 7         Scanner input = new Scanner(System.in);
 8         int n = input.nextInt();
 9         int[]a=new int[n];
10         for(int i=0;i<n;i++)
11         {
12             a[i]=input.nextInt();
13         }
14         int elem = input.nextInt();
15         System.out.println(removeElement(a,n,elem));
16     }
17     public static int removeElement(int a[],int n,int elem)
18     {
19         int s=n;
20         for(int i=0;i<n;i++)
21         {
22             if(elem == a[i])
23             {
24                 remove(a,elem);
25                 s = s - 1;
26             }
27         }
28         return s;
29     }
30    private static int[] remove(int[] arr, int num) 
31    {
32         int[] tmp = new int[arr.length - 1];
33         int idx = 0;
34         boolean hasRemove = false;
35         for (int i = 0; i < arr.length; i++) 
36         {
37             if (!hasRemove && arr[i] == num) 
38             {
39                 hasRemove = true;
40                 continue;
41             }
42             tmp[idx++] = arr[i];
43         }
44         return tmp;
45     }
46 }
原文地址:https://www.cnblogs.com/niithub/p/5795914.html