題目要求:輸入一個數組和一個值,刪除數組中等於該值得元素。不容許分配新的內存空間(即不容許建立新的數組),容許數組中的元素的順序發生變化,只要該數組在返回長度前的值正確
例如:輸入nums = [3,2,2,3], val = 3,程序返回2,且nums數組的前兩個值均爲2面試
使用一個指針
時間複雜度O(n), 空間複雜度O(1)數組
/** * @author rale * 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 RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0 ; i<nums.length ; i++){ if(nums[i] != val){ nums[index]=nums[i]; index++; } } return index; } }
使用兩個指針
時間複雜度O(n) 空間複雜度O(1)微信
/** * @author rale * 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 RemoveElement { public int removeElement(int[] nums, int val) { if(nums==null || nums.length==0){ return 0; } int leftPointer = 0; int rightPointer = nums.length-1; while(leftPointer<=rightPointer){ if(nums[rightPointer]==val){ rightPointer--; continue; } if(nums[leftPointer]==val){ nums[leftPointer] = nums[rightPointer]; rightPointer--; } leftPointer++; } return rightPointer+1; } }
leetcode的測試用例得出的性能分析發現,使用一個指針比使用兩個指針的速度更快。可是在數組的容量很是大且數組中該數字出現頻率不高的狀況下,使用兩個指針能夠明顯減小程序遍歷數組的時間。
leetcode上也給出了參考答案性能
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~測試