算法刷題訓練(2020.9.28)

1.求兩數之和

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。java

你能夠假設每種輸入只會對應一個答案。可是,數組中同一個元素不能使用兩遍。數組

示例:函數

給定 nums = [2, 7, 11, 15], target = 9指針

由於 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]code

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/two-sum排序

思路:

​ 利用雙層for循環,定義兩個指針i,j;索引

​ 看第i個數與第i個數之後的數相加是否爲target目標值,若相等則返回i,j的索引位置;不然i++。leetcode

代碼實現:

1.當前採用暴力解法

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i=0;i<nums.length-1;i++){
            for (int j = i+1; j < nums.length ; j++) {
                if((nums[i] + nums[j]) == target){
                    return new int[]{i,j};
                }
            }
        }
        throw new IllegalArgumentException("no two sum solution");
    }
}

2.採用Map集合解法

class Solution {
    public int[] twoSum(int[] nums, int target) {
         Map<Integer, Integer> map = new HashMap<>();
        // 將數組中的值和數組下標對應存入map集合中
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int j = 0; j < nums.length; j++) {
            int comp = target - nums[j];
            if (map.containsKey(comp)&&map.get(comp)!=j) {
                return new int[]{j,map.get(comp)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

ps: 採用Map集合實現將索引和數組中的數據進行一一對應,採用單重for循環將時間複雜度從O(n^2)降至O(n);利用containsKey判斷是否存在所求值,利用get排除索引號相同的狀況。rem

2.刪除排序數組中的重複項

​ 給定一個排序數組,你須要在 原地 刪除重複出現的元素,使得每一個元素只出現一次,返回移除後數組的新長度。get

​ 不要使用額外的數組空間,你必須在 原地 修改輸入數組 並在使用 O(1) 額外空間的條件下完成。

示例 1:

​ 給定數組 nums = [1,1,2],

​ 函數應該返回新的長度 2, 而且原數組 nums 的前兩個元素被修改成 1, 2。

​ 你不須要考慮數組中超出新長度後面的元素。

示例 2:

​ 給定 nums = [0,0,1,1,1,2,2,3,3,4],

​ 函數應該返回新的長度 5, 而且原數組 nums 的前五個元素被修改成 0, 1, 2, 3, 4。

​ 你不須要考慮數組中超出新長度後面的元素。

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array

思路:

​ 利用快慢指針。

​ 假若慢指針指向的值與快指針的值不相同,則慢指針+1;將快指針的值賦給慢指針所在位置。

​ 最後返回慢指針數+1便可

代碼實現:

class Solution {
    public int removeDuplicates(int[] nums) {
        // 若是數組爲空
        if (nums.length == 0){
            return 0;
        }
        // 定義快慢指針,i爲慢指針,爲快指針
        int i=0,j=1;
        for (;j < nums.length; j++) {
            if(nums[j] != nums[i]){
                i++;
                nums[i] = nums[j];
            }
        }
        return i+1;
    }
}
相關文章
相關標籤/搜索