LeetCode - RemoveElement
来源:互联网 发布:打出货单软件 编辑:程序博客网 时间:2024/06/06 13:04
/**
* 问:给出一个数组,去除指定的某个元素,并返回新数组的长度。
* 解:
* 1、返回长度很简单,只有出现一个Element,length--即可,难点是如何删除元素。
* 2、笨方法是再创建一个数组,存放不等于Element的元素。
* 3、有一个空间复杂度为O(0)的方法:
* (1)遍历数组时,出现Element后与数组最后一个元素交换。
* (2)最关键的是:交换元素后立即i--和length--!
*/
public class RemoveElement {
public int removeElement(int[] array, int element) {
int length = array.length;
int temp;
// 遍历数组
for (int i=0; i<length; i++) {
if (array[i] == element) { // 当array[i]等于element时
// 交换array[i]和尾元素
temp = array[length-1];
array[length-1] = array[i];
array[i] = temp;
// 不仅记录新数组长度,同时也影响了循环范围。
length--;
// 尾元素被放在了array[i]上,需要再判断一次。
i--;
}
}
return length;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 2, 6, 7, 9, 2};
int element = 2;
int length = new RemoveElement().removeElement(array, element);
System.out.println("删除" + element + "后新数组的长度是" + length + "。");
System.out.print("新数组是:");
for (int i=0; i<length; i++)
System.out.print(array[i] + " ");
}
- LeetCode - RemoveElement
- LeetCode 之RemoveElement
- LeetCode之RemoveElement
- leetcode 27 removeElement
- removeElement
- RemoveElement
- 27.RemoveElement(删除一个元素)--Array
- 利用ArrayUtils.removeElement()去掉List中(ˇˍˇ) 想~去的元素。。未完善
- 自定义对象new一个匿名对象以后,removeElement 对象的操作瓶颈
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- CoreData进行数据持久化存储
- Neural Networks: Learning(Andrew ng ML)
- LeetCode - UniquePaths
- jdbc一个connection 下的事务问题[转]
- myeclipse中,项目上有个叉报错,文件没有错误【解决方案】
- LeetCode - RemoveElement
- windows下php:error_log()发送邮件设置
- LeetCode - ClimbingStairs
- 关系型数据库
- Cocos2dx3.10在Windows平台搭建Android命令行编译apk打包
- LeetCode - BestTimetoBuyandSellStockI
- DB_NAME、DBID、DB_UNIQUE_NAME、SERVICE_NAME、SID、INSTANCE_NAME、GLOBAL_DATABASE_NAME
- 常用设计模式大全-详细介绍
- Linux ACL