给定一个数组和一个值,删除数组中该有和该值相等的元素,并返回新长度。要求空间复杂度为O(1)
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
思路:此题看起来很简单,但是不能用额外空间,也就是我们第一时间想到的复制数组之类的操作不能使用
1、用两个指针,和26题相似的,快慢指针
2、分析最好和最坏情况思路一的不足加以改进,
如:nums=[1,2,3,5,4],val=4.则和前4个数字的对比就是无用的
nums=[4,1,2,3,5],val=4.则和后4个数字的对比就是无用的
package Leetcode.easy; /** * 给定一个数组和一个值,删除数组中该有和该值相等的元素,并返回新长度。要求空间复杂度为O(1) * * Created by Dennis on 2018/12/19. */ public class RemoveElement { /** * 双指针法,时间复杂度为O(n),空间复杂度为O(1) * * @param nums 输入数组 * @param val 目标值 * @return int */ public static int remove(int[] nums, int val) { if (nums.length == 0) { return 0; } int i = 0; for (int j = 0; j < nums.length; j++) { if (nums[j] != val) { nums[i] = nums[j]; i++; System.out.print(nums[j] + " "); } } System.out.println(); return i; } public static void main(String[] args) { int[] nums = new int[]{3, 2, 2, 3, 3, 4, 5, 6}; int val = 3; System.out.println(remove(nums, val)); } }