leetcode移除元素27题:
一开始想到了双指针只不过,想着用快慢指针,发现思路想错了,同步双指针操作,解决问题
class Solution {
public int removeElement(int[] nums, int val) {
//进行判断数组中等于的值
//进行判断数组中等于的值
// int head = 0;
// int tail = nums.length - 1;
// if(nums.length == 1){
// if(nums[0] == val){
// return 0;
// }else{
// return 1;
// }
// }
// while (head < tail) {
// while (head < tail && nums[head] != val) {
// head++;
// }
// if (head < tail) {
// if (nums[tail] != val) {
// int temp = nums[head];
// nums[head] = nums[tail];
// nums[tail] = temp;
// head++;
// } else {
// tail--;
// }
// }else {
// break;
// }
// }
int n = nums.length;
int left = 0;
for(int i = 0; i < n;i++){
if(nums[i] != val){
nums[left] = nums[i];
left++;
}
}
return left;
}
}
总结:对于调换位置的操作往往使用双指针操作更为简单实用