zoukankan      html  css  js  c++  java
  • 27. Remove Element【leetcode】

    27. Remove Element【leetcode】

    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.

    题意:从数组中移除所有的给定的某个值,并返回数组新的长度;最后一句的意思是在新的长度后面的元素是任意的,没有顺序的要求,只要是之前数组中的元素即可,后面的元素无所谓。

     1 public class Solution {
     2     public int removeElement(int[] nums, int val) {
     3         int len=nums.length;
     4         int count = 0;
     5         for(int i=0;i<len;i++){
     6             if(nums[i]==val){
     7                 for(int j=i;j<len-1;j++){
     8                     nums[j]=nums[j+1];
     9                 }
    10                 count++;
    11             }
    12         }
    13         return len-count;
    14     }
    15 }

    解题思路:

    1. 进行循环遍历,如果只输出新数组的长度,那么只需要记录下有多少个值和标记值相同即可,最终输出数组长度-计数值
    2. 如果需要返回新的数组删除原有数组,理论上来说新建一个数组,然后将标记的不复制到新数据即可,但是题中表明,只允许在内存中进行操作,不让新建数组,那么此时如果第i个位置有标记值,那么将i+1....到最后一个值都向左挪一格即可。
    3. 实现方式请见代码
    不积跬步无以至千里,千里之堤毁于蚁穴。 你是点滴积累成就你,你的丝丝懒惰毁掉你。 与诸君共勉
  • 相关阅读:
    Poj 2391 二分答案+最大流+拆点
    POJ 1087 A Plug for UNIX 最大流
    POJ 1459 Power Network 最大流
    POJ 2112 Optimal Milking 二分答案+最大流
    POJ 1273 Drainage Ditches 最大流
    POJ 1149 PIGS 最大流
    POJ 2288 Islands and Bridges 哈密尔顿路 状态压缩DP
    The Cow Lexicon
    1523. K-inversions
    1350. Canteen
  • 原文地址:https://www.cnblogs.com/haoHaoStudyShare/p/7337047.html
Copyright © 2011-2022 走看看