2 solutions I think 1st is the better one ,but the time is longer.I think there are many same elements in test data.


  • 0
    public class Solution {
        public int removeElement(int[] nums, int val) {
            int len=nums.length;
            for(int i=0;i<len;++i)
            	if(nums[i]==val)
            		nums[i--]=nums[len---1];
            return len;
        }
    }
    
    public class Solution {
        public int removeElement(int[] nums, int val) {
            int len=nums.length;
            int res=0;
            for(int i=0;i<len;++i)
            	if(nums[i]!=val)
            		nums[res++]=nums[i];
            return res;
        }
    }

  • 0
    C
        int size = nums.length;
    	for(int i = 0; i < size; i++) {
    		if(nums[i] == val) {
    			nums[i--] = nums[--size];
    		}
    	}
    	return size;
    

    We got the same idea. This one is definitely faster than the second one. It beats 72% solutions.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.