Write a program to remove a given element from the array.
Example
Input: nums= [7,4,7,5], target=7
Output: arr = [4,5]
Approach
Java
public class RemoveElement {public static void main(String[] args) {int nums[] = { 7, 4, 7, 5};int target = 7;int n = removeElement(nums, target);for (int i = 0; i < n; i++) {System.out.print(" " + nums[i]);}}public static int removeElement(int[] nums, int val) {if (nums.length == 0)return 0;int index = 0;for (int i = 0; i < nums.length; i++) {if (nums[i] != val) {nums[index] = nums[i];index++;}}return index;}}// Time Complexity: O(n)// Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//Function to remove the target element from//arrayint RemoveElement(vector<int>& arr, int target){int j=0;int n=arr.size();for(int i=0;i<n;i++){if(arr[i]!=target)arr[j++]=arr[i];elsecontinue;}return j;}int main(){vector<int> arr;arr.push_back(7);arr.push_back(4);arr.push_back(7);arr.push_back(5);int target = 7;int n=RemoveElement(arr,target);for(int i=0;i<n;i++)cout<<arr[i]<<" ";return 0;}//Time Complexity: O(n)//Space Complexity: O(1)
No comments:
Post a Comment