关闭

leetcode 27. Remove Element

标签: leetcode数组移除元素
107人阅读 评论(0) 收藏 举报
分类:

题目

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.

public class Solution {
        public int removeElement(int[] nums, int val) {



        int count1=0;
        for(int k=0;k<nums.length;k++){
            if(nums[k]==val)
                count1++;
        }
        if(count1==nums.length)
            return 0;


        int i=0;
        int j=nums.length-1;
        int temp=0;
        int count=0;
        while(i<j){
            if(nums[j]==val){
                count++;
                j--;
                //System.out.println("count:"+count);

            }else
            {
                if(nums[i]==val){
                   temp=nums[i];
                   nums[i]=nums[j];
                   nums[j]=temp;
                   count++;
                   j--;

                }else{
                    i++;
                }
            }
        }

        //System.out.println("count:"+count);
        return (nums.length-count);

    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:57349次
    • 积分:1445
    • 等级:
    • 排名:千里之外
    • 原创:87篇
    • 转载:24篇
    • 译文:0篇
    • 评论:3条
    最新评论