zoukankan      html  css  js  c++  java
  • 力扣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};
        }
    }
  • 相关阅读:
    面试题示例
    软件测试面试题(简答)
    278. 第一个错误的版本 领扣
    hbase搭建web项目 报500错误 HTTP Status 500
    java API连接虚拟机上的hbase
    java程序连接hive数据库遇到的问题
    java程序向hdfs中追加数据,异常以及解决方案
    创建一个简单的maven的web程序
    java连接hbase时出现....is accessible from more than one module:
    导师双选制系统
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15386246.html
Copyright © 2011-2022 走看看