[LeetCode][Java] 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.

题意:

给定一个数组和一个值,在这个数组中移除所有这个值的元素,返回一个新的长度的数组。

数组中的元素顺序可以变化。数组中超过新的长度之外的元素并不考虑。

算法分析:

/**
 * 算法比较简单,但是要考虑的特殊情况(例子)比较多
 * 设置两个指针,头指针放在数组起始位置,尾指针放在数组的结尾的位置
 * 头指针从头到尾进行遍历,遇到目标元素,就和尾指针的元素互换
 * 重复上述过程,直到两个指针相遇,这样,所有的目标元素全部放到了数组的最后,不同于目标元素的各种元素全部位于数组的前面
 * 最后统计数组的前面的不同元素的个数,并返回
 * 时间复杂度O(n),空间复杂度O(n)
 */ 

AC代码:

public class Solution 
{

    public   int removeElement(int[] nums, int val) 
    {
		boolean flag=true;
		if(nums.length==0) return 0;
		if(nums.length==1) 
		{
			if(nums[0]==val)
			{
			    nums=new int[0];
			    return 0;
			}
			else return 1;
		}
		for(int i=0;i<nums.length;i++)
		{
		    if(nums[i]==val) flag=true;
		    else 
		    {
		        flag=false;
		        break;
		    }
		}
		if(flag) 
		{
		    nums=new int[0];
		    return 0;
		}
		int startindex=0;
		int endindex=nums.length-1;
		int tem=0;
		while(startindex!=endindex)
		{
			tem=0;
			if(nums[startindex]==val&&nums[endindex]!=val)
			{
				tem=nums[startindex];
				nums[startindex]=nums[endindex];
				nums[endindex]=tem;
				if(startindex<endindex) startindex++;
				if(startindex<endindex) endindex--;
			}
			else if(nums[startindex]==val&&nums[endindex]==val)
				endindex--;
			else if(nums[startindex]!=val&&nums[endindex]==val)
			{
				if(startindex<endindex) startindex++;
				if(startindex<endindex) endindex--;
			}
			else if(nums[startindex]!=val&&nums[endindex]!=val)
			{
				if(startindex<endindex) startindex++;
			}
		}
    	int k=0;
		for(int i=0;i<nums.length;i++)
    	{
    		if(nums[i]!=val)
    			k++;
    	}
		return k;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值