27. Remove Element
来源:互联网 发布:中国 改革开放 知乎 编辑:程序博客网 时间:2024/05/17 07:02
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
题目主要意思:给你一个数组和一个数字,返回将数组中与数字相同的部分去掉后的长度len,以及这个数组的前len位是与数字不相同的部分
自己做,如下所示:
public static int removeElement(int[] nums, int val) {
int count = 0;
int len = nums.length;
if(len == 0 || nums == null){
return 0;
}
Arrays.sort(nums);
for(int i = 0; i < len ; i++){
if(nums[i] == val){
count++;
nums[i] = nums[len-count];
}else if(count > 0)
break ;
}
return len - count;
int count = 0;
int len = nums.length;
if(len == 0 || nums == null){
return 0;
}
Arrays.sort(nums);
for(int i = 0; i < len ; i++){
if(nums[i] == val){
count++;
nums[i] = nums[len-count];
}else if(count > 0)
break ;
}
return len - count;
}
提交后看到别人写的,如下所示:
public static int removeElement(int[] nums, int val) {
int count = 0;
int len = nums.length;
if(len == 0 || nums == null){
return 0;
}
for(int i = 0;i < len ;i++){
if(nums[i] != val){
nums[count++] = nums[i];
}
}
return count;
}
int count = 0;
int len = nums.length;
if(len == 0 || nums == null){
return 0;
}
for(int i = 0;i < len ;i++){
if(nums[i] != val){
nums[count++] = nums[i];
}
}
return count;
}
阅读全文
0 0
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- 27.Remove Element
- [Leetcode] 27.Remove Element
- 27. Remove Element
- 27. Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- 27. Remove Element
- 27. Remove Element
- 27. Remove Element
- Leetcode 27. Remove Element
- 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 27. Remove Element
- 复习
- cuda编程基础概念语法
- 杀死oracle进程
- nginx之worker启动分析
- Java反射
- 27. Remove Element
- SQLite数据库锁问题
- scala学习笔记(1)
- C# Winform Datagridview 排序 多线程操作数据 遇到的坑
- 查找错误千万要拓展思维!
- eclipse空间目录管理——查看与删除
- YOLO
- MATLAB---matlab 中的bwlabel函数
- DAO层,Service层,Controller层、View层