首页 > 代码库 > 【Leetcode】27. Remove Element
【Leetcode】27. Remove Element
Question:
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.
题目说明:
输入一个int类型数组:nums = [3,2,2,3]
以及一个数组内的数字:val = 3
要求输出去除val之后数组长度,并且数组要将所有val覆盖掉;
SHOW YOU THE CODE
1 package easy; 2 3 public class L27 { 4 // Remove Element 5 public int removeElement(int[] nums, int val) { 6 int ans; 7 int len = nums.length; 8 ans = len; 9 int count = 0; 10 for (int i = 0; i < len; i++) { 11 if (nums[i] == val) { 12 ans--; 13 14 } else { 15 nums[count] = nums[i]; 16 count++; 17 } 18 } 19 for (int i = 0; i < count; i++) { 20 System.out.println(nums[i]); 21 } 22 System.out.println(ans); 23 return ans; 24 } 25 26 public static void main(String[] args) { 27 L27 l27 = new L27(); 28 int[] nums = { 2, 2, 2, 2, 3 }; 29 int val = 3; 30 l27.removeElement(nums, val); 31 } 32 }
注:
①题目说明需要改变原数组,将val覆盖掉:
else { nums[count] = nums[i]; count++; }
这段代码中count记录除去val之后的数字个数,可以覆盖掉原来数组
②写给你看看,今天的代码写的超级爽快,10几分钟 oh yeah
【Leetcode】27. Remove Element
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。