TreeviewCopyright © aleen42 all right reserved, powered by aleen42

645. 错误的集合

https://leetcode-cn.com/problems/set-mismatch/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-26 13:00:38
 * @LastEditTime: 2020-08-26 13:04:46
 * @Description: https://leetcode-cn.com/problems/set-mismatch/
 * @FilePath: \leetcode-googtech\#645. Set Mismatch\Solution.java
 * @WebSite: https://algorithm.show/
 */

class Solution {

    // 使用额外数组法
    public int[] findErrorNums(int[] nums) {
        // 初始化计数数组
        int[] counter = new int[nums.length + 1];
        // 遍历 nums 数组,将其元素值作为 counter 数组的索引值,而将每个元素出现的次数作为其元素值
        for(int num : nums) counter[num]++;
        // 初始化结果数组
        int[] result = new int[2];
        // 遍历计数数组
        for(int i = 1; i < counter.length; i++) {
            // 若当前索引下的元素值等于零则证明当前索引值即为丢失的数值
            if(counter[i] == 0) {
                result[1] = i;
            // 若等于二则证明当前索引值即为重复出现的数值
            } else if(counter[i] == 2) {
                result[0] = i;
            }
        }
        // 返回结果数组
        return result;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-26 13:00:43
LastEditTime: 2020-08-26 13:05:01
Description: https://leetcode-cn.com/problems/set-mismatch/
FilePath: \leetcode-googtech\#645. Set Mismatch\Solution.py
WebSite: https://algorithm.show/
'''

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        # 初始化结果列表并对 nums 进行排序处理
        result, nums = [], sorted(nums)
        # 从头到尾遍历数组
        for i in range(len(nums) - 1):
            # 若相邻元素相同则将其添加到结果列表中,然后结束遍历
            if nums[i] == nums[i + 1]:
                result.append(nums[i])
                break
        # 从索引值一开始从头到尾遍历数组
        for i in range(1, len(nums) + 1):
            # 若当前索引值不在数组 nums 中则将其添加到结果列表中,然后结束遍历
            if i not in nums:
                result.append(i)
                break
        # 返回结果
        return result
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""