zoukankan      html  css  js  c++  java
  • LeetCode 442. Find All Duplicates in an Array

    原题链接在这里:https://leetcode.com/problems/find-all-duplicates-in-an-array/

    题目:

    Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

    Find all the elements that appear twice in this array.

    Could you do it without extra space and in O(n) runtime?

    Example:

    Input:
    [4,3,2,7,8,2,3,1]
    
    Output:
    [2,3]

    题解:

    类似Find All Numbers Disappeared in an Array. iterate nums array时把nums[Math.abs(nums[i]-1)]标负,但需要先检查是否已经标过负了。若是说明是出现过一次. 把index+1添加到res中.

    Time Complexity: O(nums.length). Space: O(1).

    AC Java: 

     1 public class Solution {
     2     public List<Integer> findDuplicates(int[] nums) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         if(nums == null || nums.length == 0){
     5             return res;
     6         }
     7         
     8         for(int i = 0; i<nums.length; i++){
     9             int index = Math.abs(nums[i])-1;
    10             if(nums[index] < 0){
    11                 res.add(index + 1);
    12             }else{
    13                 nums[index] = -nums[index];
    14             }
    15         }
    16         return res;
    17     }
    18 }

    可以吧num[i] swap到对应的index = nums[i]-1上面.

    第二遍iterate时如果nums[i] !=i+1. nums[i]就是duplicate的. 加入res中.

    Time Complexity: O(n). Space: O(1), regardless res.

    AC Java:

     1 class Solution {
     2     public List<Integer> findDuplicates(int[] nums) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         for(int i = 0; i<nums.length; i++){
     5             if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i]!=nums[nums[i]-1]){
     6                 swap(nums, i, nums[i]-1);
     7                 i--;
     8             }      
     9         }
    10         
    11         for(int i = 0; i<nums.length; i++){
    12             if(nums[i] != i+1){
    13                 res.add(nums[i]);
    14             }
    15         }
    16         
    17         return res;
    18     }
    19     
    20     private void swap(int [] nums, int i, int j){
    21         int temp = nums[i];
    22         nums[i] = nums[j];
    23         nums[j] = temp;
    24     }
    25 }
  • 相关阅读:
    构建git+gerrit+repo的Android代码服务器
    简单学习:repo入门
    git checkout 命令详解
    python学习第一天
    window下的git工具msysgit的使用
    git基本操作
    echarts 使用示例
    管道命令
    jquery修改文档结构
    JavaScript正则表达式
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6241994.html
Copyright © 2011-2022 走看看