Leetcode OJ 27 Remove Element [Easy]
来源:互联网 发布:vb label背景透明 编辑:程序博客网 时间:2024/06/05 08:19
Leetcode OJ 27 Remove Element [Easy]
题目描述:
Given anarray and a value, remove all instances of that value in place and return thenew length.
Do notallocate extra space for another array, you must do this in place with constantmemory.
Theorder of elements can be changed. It doesn't matter what you leave beyond thenew length.
Example:
Giveninput array nums = [3,2,2,3], val = 3
Yourfunction should return length = 2, with the first two elements of nums being 2.
题目理解:
给定一个数组和一个数值,移除数组中所有所给的数值,返回新数组的长度。
测试用例:
功能测试:数组中有存在1个、2个、多个所给数值;
边界测试:数组是null;数组长度是1;数组中所有的数字都是所给数字;数组中不存在所给数值;
分析:
1. 维护两个指针,check从数组头开始向后遍历,add从数组尾开始向前移动,Add向前移动,所指的数字不等于所给的val;
2. check从头开始遍历,如果所指的数字是val,则用add所指的值替换,add所指的位置的数字删去(在leetcode这道题中,将其替换为val即可通过),add向前移动(一直前移直到所值数字不等于val),check后移一位继续判断;
3. 直到check的移动到add的后面为止,此时add + 1是新数组的长度;
解答:
class Solution { public int removeElement(int[] nums, intval) { int check= 0,add = nums.length - 1; while(add> 0 &&nums[add] == val){ add --; } if(add== 0){ if(nums[add]== val) return 0; else return 1; } while(add> 0 &&check < nums.length -1&& check <= add){ if(nums[check]== val){ nums[check] = nums[add]; check ++; nums[add] = val; while(nums[add] == val) add --; } else{ check ++; } } return add + 1; }}
- Leetcode OJ 27 Remove Element [Easy]
- [Leetcode 27, easy] Remove Element
- LeetCode OJ-27-Remove Element
- LeetCode-27-Remove Element(数组)-Easy
- LeetCode OJ:Remove Element
- LeetCode OJ - Remove Element
- [LeetCode OJ]Remove Element
- LeetCode OJ Remove Element
- <LeetCode><Easy> 28 Remove Element
- leetcode 27. Remove Element (EASY)
- 【LeetCode OJ 027】Remove Element
- <LeetCode OJ> 27. Remove Element
- [LeetCode OJ]27.Remove Element
- Easy 27题 Remove Element
- [LeetCode] 027. Remove Element (Easy) (C++)
- 【LeetCode】2(7)Remove Element(Easy)
- Leetcode 27. Remove Element (Easy) (cpp)
- Leetcode 27. Remove Element (Easy) (java)
- 【51Nod1444】破坏道路
- java每日一练
- MySQL I/O 问题
- JAVA学习笔记
- JAVA多线程的三种实现方式
- Leetcode OJ 27 Remove Element [Easy]
- git ssh生成
- pat 乙级 1030. 完美数列(25)
- js的一些积累
- This application failed to start because it could not find or load the Qt platform plugin "xcb" in "
- python使用sqlalchemy中间件对MYSQL数据库进行创建、查询、删除操作
- 基于JavaSwing+MySql的学生信息管理系统
- 141. Linked List Cycle
- 面试题:完全二叉树699个节点,则叶子节点有多少个?