Leetcode: Remove Elements
LeetCode Elements remove
2023-09-11 14:14:08 时间
Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length.
一次性通过的,比较顺利,从读题到编写到检查到通过,14分50秒,我在不断进步中,相信经过一段时间联系,这种题可以一眼就写出来,不超过5分钟。
这道题应该说方法跟 Remove Duplicates from sorted Array挺类似的
My Solution:
1 public class Solution { 2 public int removeElement(int[] A, int elem) { 3 int count = 0; 4 for(int i=0; i<A.length; i++){ 5 if(A[i] != elem){ 6 A[count] = A[i]; 7 count++; 8 } 9 } 10 return count; 11 } 12 }
再贴个另外两个人的solution,以便对照参考,比较优劣:
Solution 1: 这个想法有点曲折
1 public class Solution { 2 public int removeElement(int[] A, int elem) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int i=0, j=A.length-1; 6 7 while(i<=j){ 8 if(A[i]==elem) 9 swap(A,i,j--); 10 else 11 i++; 12 } 13 return j+1; 14 } 15 16 public void swap(int[] A,int i, int j){ 17 int temp = A[i]; 18 A[i] = A[j]; 19 A[j] = temp; 20 } 21 }
Solution 2: 跟我的想法一致
1 public class RemoveElement { 2 public int removeElement(int[] A, int elem) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if (A.length == 0) { 6 return 0; 7 } 8 int counter = 0; 9 for (int i = 0; i < A.length; i++) { 10 if (A[i] != elem) { 11 A[counter] = A[i]; 12 counter++; 13 } 14 } 15 return counter; 16 17 } 18 }
相关文章
- Leetcode: Integer Break
- Leetcode: Majority Element
- Remove Linked List Elements -- leetcode
- LeetCode高频题38. 外观数列
- [LeetCode]剑指 Offer 47. 礼物的最大价值
- leetcode竞赛记录-第266场周赛
- LeetCode 51 N-Queens
- [LeetCode] 1299. Replace Elements with Greatest Element on Right Side 将每个元素替换为右侧最大元素
- [LeetCode] 1261. Find Elements in a Contaminated Binary Tree 在受污染的二叉树中查找元素
- [LeetCode] Complex Number Multiplication 复数相乘
- [LeetCode] Russian Doll Envelopes 俄罗斯娃娃信封
- [LeetCode] 347. Top K Frequent Elements 前K个高频元素
- [LeetCode] 15. 3Sum 三数之和
- [LeetCode] 138. Copy List with Random Pointer 拷贝带有随机指针的链表
- leetcode 257. Binary Tree Paths 二叉树的所有路径(简单)