• 27. Remove Element


    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.

    给定一个无序数组,和一个指定数字,返回去掉该数字后数组的长度,要求不能开额外的内存

    C++(3ms):

     1 class Solution {
     2 public:
     3     int removeElement(vector<int>& nums, int val) {
     4         int len = nums.size() ;
     5         if (len < 1)
     6             return 0 ;
     7         int res = 0 ;
     8         for (int i = 0 ; i < len ; i++){
     9             if (nums[i] != val){
    10                 if (i != res){
    11                     nums[res] = nums[i] ;
    12                 }
    13                 res++ ;
    14             }
    15         }
    16         return res ;
    17     }
    18 };

    java(13ms):

     1 class Solution {
     2     public int removeElement(int[] nums, int val) {
     3         int res = 0 ;
     4         for(int i = 0 ; i < nums.length ; i++){
     5             if (nums[i] != val){
     6                 nums[res++] = nums[i] ;
     7             }
     8         }
     9         return res ;
    10     }
    11 }
  • 相关阅读:
    java--exceptions
    java-interface
    Java笔记
    memcpy
    const 关键字
    LeeCode整数 反转
    函数调用运算符笔记
    cvCreateImage
    c++继承笔记1
    虚拟机下的debian无法登陆
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7543782.html
Copyright © 2020-2023  润新知