Remove Element
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
思路:此题和26题一脉相承,算法上不难,具体如代码所示:
public class Solution {
public int removeElement(int[] nums, int val) {
int len = nums.length;
int tempLen = len;
int step = 0;//每个元素需要向前转移的距离
for(int i = 0; i < len; i++){
if(nums[i] == val){
step++;//若相等步长+1
tempLen--;//每一个相等的元素长度减少1
}else{
nums[i-step] = nums[i];//元素前移n个步长
}
}
return tempLen;
}
}
最后
以上就是彩色大山最近收集整理的关于leetCode 27.Remove Element (删除元素) 解题思路和方法的全部内容,更多相关leetCode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复