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.

    题目的要求是这个,最初的想法非常简单,首先用一个变量length记录下数组A的长度,其次对A中的元素开始遍历比较,如果A中的元素和ele相同,则将length减1

            int length = A.length;
            for(int i = 0;i<A.length;i++){
                if(A[i] == elem){
                    length = length - 1;
                }
            }
            return length;        

    提交之后出现了错误,我觉得最主要的原因可能是没有改变原来的数组,只是针对数组的长度变化。

    修改之后:

    public class Solution {
        public int removeElement(int[] A, int elem) {
            int length = 0;
            for(int i = 0;i<A.length;i++){
                if(A[i] != elem){
                    A[length] = A[i];
                    length = length + 1;
                }
            }
            return length;
        }
    }

    提交成功,之后看了网上看了别人的方法,大部分人都是如果遇到elem,就将它调整到数组的后面去,

    public class Solution {
        public int removeElement(int[] A, int elem) {
            int length = A.length;
            for(int i = 0;i<length;i++){
                if(A[i] == elem){
                    A[i] = A[length-1];
                    i--;
                    length--;
                }
            }
            return length;
        }
    }

    觉得它i和length处理那里很好,拿来借鉴。

  • 相关阅读:
    类图的基本知识
    设计模式——单例模式
    解决phpcms V9 推荐位无法排序
    PHPCMS 多站点管理切换问题
    天天团购系统-简单的目录结构
    php的时间输出格式
    天天团购--源码目录结构
    天天团购系统--部分模板语法
    PHP json数据格式化方法
    PHP json_encode中文乱码解决方法
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4381234.html
Copyright © 2011-2022 走看看