LeetCode | Remove Element(删除指定元素)
来源:互联网 发布:纸张分切软件 编辑:程序博客网 时间:2024/05/16 17:48
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.
删除数组中制定的元素,返回新的长度题目解析
这道题和上一道题目很类似,也是遇到不合法的数据用后面的数据替换,不过这里的j不是从前往后遍历, 而是从后向前遍历,找到第一个不是关键字的数据放置到arr[i]的位置,然后i+1继续遍历。注意一些细节,比如输入的参数不合法(空指针,长度为零等情况),这道题目就不难了。
另:
也可以跟上一题一样,i和j都是从前向后遍历,当arr[j]的值和key的值不相等就对arr[i]进行赋值。
#include <stdio.h>#include <stdlib.h>int RemoveElement(int arr[],int len,int key);int main(){ int n,key; int arr[20]; while(scanf("%d %d",&n,&key) != EOF){ for(int i = 0;i < n;++i) scanf("%d",&arr[i]); int len = RemoveElement(arr,n,key); printf("len = %d\n",len); for(int i = 0;i < len;++i){ printf("%d ",arr[i]); } putchar('\n'); } return 0;}int RemoveElement(int arr[],int len,int key){ int i = 0,j = len-1; if(arr == NULL || len <=0) return 0; while(i <= j){ if(arr[i] == key){ while(i<=j){ if(arr[j] != key) break; --j; } if(i>j) //当最后的数据全部都是要删除的关键字的时候,会产生这样的情况 break; arr[i] = arr[j]; //将后面的数据放置到要删除的数据的位置 --j; } ++i; } //最后返回的i的位置,不是合法的数据,从0--> i-1位置才是我们要求解的 return i; //这时的返回值表示长度}
0 0
- LeetCode | Remove Element(删除指定元素)
- LeetCode 27. Remove Element(删除元素)
- LeetCode OJ 之 Remove Element (删除指定元素)
- leetcode:Remove Element删除元素
- [LeetCode-27] Remove Element(从数组删除指定的元素)
- 删除序列中的指定元素 Remove Element
- Remove Element 数组删除指定的元素
- 27. Remove Element 删除指定元素
- (LeetCode)Remove Element --- 去掉指定元素
- leetcode:Remove Element (删除给定元素)【面试算法题】
- [LeetCode-27] Remove Element(数组元素删除)
- Remove Element 删除元素
- Remove Element(删除数组某一元素)
- Leetcode 27 Remove Element(移除数组中的指定元素)
- Remove Element 数组中删除给定元素 @ LeetCode
- LeetCode:Remove Element(删除数组中的特定元素)
- leetCode 27.Remove Element (删除元素) 解题思路和方法
- [C++]LeetCode 27: Remove Element(删除数组中指定元素)
- 华为OJ:找出字符串中第一个只出现一次的字符
- 折腾开源WRT的AC无线路由之路-3
- Android ANR介绍与避免
- java类的equals hashcode
- Android : dip/dp与px(pixel)之间的相互转换
- LeetCode | Remove Element(删除指定元素)
- 面向对象软件设计原则
- 7/9
- 侧边栏(使用Support Library 4提供的扩展组件)
- listview优化
- leetcode: Pascal's Triangle II
- 网络流小结
- 面试技巧
- 详细解析Java中抽象类和接口的区别