zoukankan      html  css  js  c++  java
  • LeetCode 27. Remove Element 题解

    Total Accepted: 122406 Total Submissions: 356377 Difficulty: Easy
    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.

    public class Solution {
        public int removeElement(int[] nums, int val) {
            // if (nums.length == 0) 
            //     return 0;
                
            // int i = 0, j = nums.length - 1;
        
            // while ( i <= j ){
            //     if ( nums[i] == val ){
            //         int temp = nums[i];
            //         nums[i] = nums[j];
            //         nums[j] = temp;
            //         j--;
            //     } else {
            //         i++;
            //     }
            // }
            
            // return j + 1;
            
            int newIndex = 0;  
            for (int oldIndex = 0; oldIndex < nums.length; ++oldIndex) {  
                if (nums[oldIndex] != val) {  
                    nums[newIndex] = nums[oldIndex];//可以覆盖val所占空间
                    newIndex++;
                }   
            }  
            return newIndex;  
            
        }
    }
    
  • 相关阅读:
    Linux let 命令
    perl hash array 嵌套 push
    Perl CGI编程
    Perl关联数组用法集锦
    关于反射和动态代理
    SpringBoot与web开发
    Springboot与日志
    Spring Boot
    SpringBoot的自动配置原理
    Spring MVC执行流程
  • 原文地址:https://www.cnblogs.com/liveandlearn/p/5583361.html
Copyright © 2011-2022 走看看