LeetCode编程练习 - Remove Element学习心得
2017-09-21 16:23
465 查看
题目:
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 arraynums
=
=
Your function should return length = 2, with the first two elements ofnums
being 2.
给定一个数组和一个值,删除该值的所有实例并返回新的长度。元素的顺序可以更改。
思路:
我的思路,定义一个数组num[]和一个指定值,定义一个变量来表示它的长度,定义一个索引值,然后判断索引值指向的数字是否与指定值相同,若相同则跳出,若不相同则将索引值赋值给变量。
运行程序显示输出为空字符串,在确保思路没有问题的情况下查看解决方案,解决方案中是直接判断二者不相同赋值,思路与我的并无异,只是我的写法稍微啰嗦了一些。我又看了一下我的程序,发现在赋值后并未对变量进行任何处理,也就是说循环完一遍变量i的值仍为0,在赋值后添加i++,运行结果仍为空字符串,我将break语句去掉,在判断相等的情况下不管它,运行结果显示,也就是说当我判断相等的时候break语句直接跳出程序。突然想到break是跳出整个循环,应该使用continue,结束单次循环。
运行结果如下:
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 arraynums
=
[3,2,2,3],val
=
3
Your function should return length = 2, with the first two elements ofnums
being 2.
给定一个数组和一个值,删除该值的所有实例并返回新的长度。元素的顺序可以更改。
思路:
我的思路,定义一个数组num[]和一个指定值,定义一个变量来表示它的长度,定义一个索引值,然后判断索引值指向的数字是否与指定值相同,若相同则跳出,若不相同则将索引值赋值给变量。
运行程序显示输出为空字符串,在确保思路没有问题的情况下查看解决方案,解决方案中是直接判断二者不相同赋值,思路与我的并无异,只是我的写法稍微啰嗦了一些。我又看了一下我的程序,发现在赋值后并未对变量进行任何处理,也就是说循环完一遍变量i的值仍为0,在赋值后添加i++,运行结果仍为空字符串,我将break语句去掉,在判断相等的情况下不管它,运行结果显示,也就是说当我判断相等的时候break语句直接跳出程序。突然想到break是跳出整个循环,应该使用continue,结束单次循环。
运行结果如下:
相关文章推荐
- LeetCode编程练习 - Linked List Cycle学习心得
- LeetCode编程练习 - Isomorphic Strings学习心得
- LeetCode编程练习 - Contains Duplicate学习心得
- LeetCode编程练习 - Intersection of Two Linked Lists学习心得
- LeetCode编程练习 - Search Insert Position学习心得
- LeetCode编程练习 - Best Time to Buy and Sell Stock II学习心得
- LeetCode编程练习 - Remove Linked List Elements学习心得
- LeetCode编程练习 - Contains Duplicate Ⅱ学习心得
- LeetCode编程练习 - Reverse Linked List学习心得
- LeetCode 编程练习 - Two Sum II - Input array is sorted学习心得
- LeetCode编程练习 - Palindrome Linked List学习心得
- LeetCode编程练习 - Move Zeroes学习心得
- LeetCode编程练习 - Intersection of Two Arrays II学习心得
- LeetCode编程练习 - Majority Element学习心得
- LeetCode编程练习 - Valid Anagram学习心得
- LeetCode编程练习 - Delete Node in a Linked List学习心得
- LeetCode编程练习 - Reverse Integer学习心得
- LeetCode编程练习 - Plus One学习心得
- LeetCode编程练习 - Add Binary学习心得
- LeetCode编程练习 - Two Sum学习心得