每天坚持发两篇文章?
昨天原力值150,今天146
资源分从135,掉到129,今天掉到127
这啥逻辑?
问下客服,也许平台在核算中
从来就不知道原力值有什么用
数组是以引用的方式传递的
数组中的元素无法真正移除,只能靠后一个元素覆盖前一个元素,返回移除后的数组没有意义
题目:LeetCode.27
写法一:暴力解法
使用两个for循环,第一个for循环遍历数组,第二个for循环更新数组。
class Solution {
public int removeElement(int[] nums, int val) {
int length = nums.length;
for (int i = 0 ; i < length ; i++){
if (nums[i] == val){
for (int j = i + 1 ; j < length ; j++){
nums[j -1] = nums[j];
}
i--;
length--;
}
}
return length;
}
}
// 时间复杂度:O(n^2)
// 空间复杂度:O(1)
写法2:双指针算法
通过一个慢指针和一个快指针在一个for循环下完成两个for循环的工作。
class Solution {
public int removeElement(int[] nums, int val) {
int slowindex = 0;
for(int fastindex = 0 ; fastindex < nums.length ; fastindex++){
if (nums[fastindex] != val){
nums[slowindex] = nums[fastindex];
slowindex++;
}
}
return slowindex;
}
}
// 时间复杂度:O(n)
// 空间复杂度:O(1)
写法3:相向双指针法:
class Solution {
public int removeElement(int[] nums, int val) {
int left = 0;
int right = nums.length - 1;
while(right >= 0 && nums[right] == val) right--;
//将right移到从右数第一个值不为val的位置
while(left <= right) {
if(nums[left] == val) {
nums[left] = nums[right];
right--;
}
left++;
while(right >= 0 && nums[right] == val) right--;
}
return left;
}
}
// 时间复杂度:O(n)
// 空间复杂度:O(1)