?LeetCode刷題實戰(zhàn)27:移除元素
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?移除元素,我們先來看題面:
https://leetcode-cn.com/problems/remove-element/
Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length.
題意
樣例
示例 1:
給定 nums = [3,2,2,3], val = 3,
函數(shù)應(yīng)該返回新的長度 2, 并且 nums 中的前兩個元素均為 2。
你不需要考慮數(shù)組中超出新長度后面的元素。
示例?2:
給定 nums = [0,1,2,2,3,0,4,2], val = 2,
函數(shù)應(yīng)該返回新的長度 5, 并且 nums 中的前五個元素為 0, 1, 3, 0, 4。
注意這五個元素可為任意順序。
你不需要考慮數(shù)組中超出新長度后面的元素。
題解
public?int?removeElement(int[] nums, int?val)?{
????int?i = 0;
????for?(int?j = 0; j < nums.length; j++) {
????????if?(nums[j] != val) {
????????????nums[i] = nums[j];
????????????i++;
????????}
????}
????return?i;
}
上期推文:
評論
圖片
表情
