forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove_element_from_array.java
93 lines (73 loc) · 2.1 KB
/
remove_element_from_array.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Remove Element from the Array
For a given array of integers arr[], and a key value
remove the key values from the array if present, and
return the new size of the array thus obtained.
It is given that removal of all the elements should be in-place,
there should be no use of extra space.
*/
import java.util.Scanner;
import java.util.Arrays;
class remove_elements_from_array
{
//function to remove the key value
//from arrray if present
public int removeKey(int arr[], int key)
{
//simply returning for an empty array
if(arr.length == 0){
return 0;
}
int newSize = 0;
for(int pass = 0; pass < arr.length; pass++)
{
if(arr[pass] != key)
{
arr[newSize] = arr[pass];
newSize++;
}
}
return newSize;
}
//driver method
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int size = sc.nextInt();
System.out.println("Enter the key value: ");
int key = sc.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements of array: ");
for(int i = 0; i < size; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("New size of array thus formed after the removal of "+key+" is : ");
System.out.print(removeKey(arr, key));
System.out.println();
}
}
/*
EXAMPLES:-
Example 1:
Input--
Enter the size of the array: 5
Enter the key value: 6
Enter the elements of array: 2 1 8 33 6
New size of array thus formed after the removal of 6 is : 4
Example 2:
Input--
Enter the size of the array: 3
Enter the key value: 1
Enter the elements of array: 6 80 44
New size of array thus formed after the removal of 1 is : 3
Example 3:
Input--
Enter the size of the array: 1
Enter the key value: 0
Enter the elements of array: 1
New size of array thus formed after the removal of 0 is : 1
TIME COMPLEXITY --> O(N)
SPACE COMPLEXITY --> O(1)
*/