力扣27题、26题、167题(移除元素,两数之和)

27、移除元素

基本思想:

双指针法(快慢指针)

具体实现:

代码:

class Solution {
    public int removeElement(int[] nums, int val) {
        int fastIndex = 0;
        int slowIndex;
        for (slowIndex = 0; fastIndex < nums.length; fastIndex++){
            if (nums[fastIndex] != val){
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;
    }
}

26、删除有序数组中的重复项

基本思想:

快慢指针

具体实现:

fast指针先走,

找到一个不重复的元素填到slow的位置,并让slow前进一步

fast遍历完整个数组以后

【0,。。slow】就是不重复元素

代码:

class Solution {
    public int removeDuplicates(int[] nums) { 
        int fastIndex = 1;
        int slowIndex ;
        for (slowIndex = 1; fastIndex < nums.length; fastIndex++){
            if (nums[fastIndex] != nums[fastIndex-1]){
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;
    }
class Solution {
    public int removeDuplicates(int[] nums) { 
        int fastIndex = 1;
        int slowIndex ;
        for (slowIndex = 0; fastIndex < nums.length; fastIndex++){
            if (nums[fastIndex] != nums[slowIndex]){
                slowIndex++;
                nums[slowIndex] = nums[fastIndex];
            }
        }
        return slowIndex+1;
    }
}

167、两数之和II

基本思想:

左、右指针

具体实现:

类似于二分搜索

代码:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left < right){
            int sum = numbers[left] + numbers[right];
            if (sum == target){
                return new int[]{left + 1, right + 1};
            }else if (sum < target){
                left++;
            }else {
                right--;
            }
        }
        return new int[]{-1, -1};
    }
}
原文地址:https://www.cnblogs.com/zhaojiayu/p/15386246.html