Remove Element
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.
注:这道题使用了简单选择排序的思想。将数组从头开始向后遍历,当发现A[i]==elem时,将该数组最后一个位置的元素进行交换(最后一个位置随着删除元素,不断的变化)。
public class Solution { public int removeElement(int[] A, int elem) { int len = A.length-1; int i = 0; int temp; while(i <= len){ if(A[i] == elem){ temp = A[len]; A[len] = A[i]; A[i] =temp; --len; } else{ i++; } } return len+1; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步