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

    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.


    题解:用一个len变量记录当前数组的长度。每次遇到元素elem,就把len-1指着的元素换到elem元素所在的地方,然后把len--。要注意的地方就是elem在数组结尾的时候,len减一减到和i相等的时候,就不能再减了,应该结束遍历,返回len的值。

    代码如下:

     1 class Solution {
     2 public:
     3     int removeElement(int A[], int n, int elem) {
     4         int len = n;
     5         for(int i = 0;i < len;i ++){
     6             if(A[i] == elem){
     7                 while(A[len - 1] == elem && len > i)
     8                     len--;
     9                 A[i] = A[len-1];
    10                 if(len > i)
    11                     len --;
    12             }
    13         }
    14         /*for(int i= 0;i < len;i++)
    15             cout <<A[i]<<endl;*/
    16         return len;
    17     }
    18 };

     还有一种正序的想法,就是设置一个puthere指针,每次发现和elem不想等的元素,就放到puthere所指向的位置;

    java代码如下:

     1 public class Solution {
     2     public int removeElement(int[] A, int elem) {
     3         int puthere = 0;
     4         int n = A.length;
     5         for(int i = 0;i < A.length;i++){
     6             if(A[i] != elem){
     7                 A[puthere] = A[i];
     8                 puthere++;
     9             }
    10             else {
    11                 n--;
    12             }
    13         }
    14         return n;
    15     }
    16 }
  • 相关阅读:
    css 修改滚动条
    target和currentTarget的区别
    css 绘制对话框三角符号
    sass/less/stylus css编译
    angular 国际化
    angularjs中展示富文本编辑器文本,向DOM中插入元素
    炫酷动画效果,小球洒落,树木开花,深林效果
    angular插件合集
    css3 倒影
    Promise简介
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3778606.html
Copyright © 2011-2022 走看看