【问题标题】:ArrayList vs HashMap time complexityArrayList vs HashMap 时间复杂度
【发布时间】:2021-04-17 01:38:23
【问题描述】:

场景如下:

您有 2 个字符串 (s1, s2) 并想检查一个是否是另一个的排列,因此您生成假设 s1 的所有排列并存储它们,然后迭代并与 s2 进行比较,直到找到或没有.

现在,在这种情况下,我正在考虑在严格考虑时间复杂度时是使用 ArrayList 还是使用 HashMap 更好,因为我相信两者都有 O(N) 空间复杂度。

根据 javadocs,ArrayList 的搜索复杂度为 O(N),而 HashMap 的搜索复杂度为 O(1)。如果是这种情况,是否有任何理由支持在这里使用ArrayList 而不是HashMap,因为HashMap 会更快?

我能想到的唯一潜在缺点是,如果您执行key = value(即{k = "ABCD", v = "ABCD"} 等)之类的操作,您的(k,v) 对可能会有点奇怪。

【问题讨论】:

  • 为什么要这样实现检查?
  • @chrylis-cautiouslyoptimistic- 因为这是我想出的算法。
  • 生成排列是非常昂贵的,更不用说这样做的时间和空间复杂性了。还有另一种更便宜的检查方法。它确实涉及重新排序字符串。
  • 生成所有排列是 O(n!),这真的很糟糕。它甚至比指数还要糟糕。为了了解 O(n!) 有多糟糕,假设您试图通过反复洗牌来对一副纸牌进行排序,直到所有纸牌随机排列。该算法也将是O(n!)
  • 你需要想出一个更好的算法。想想吧。

标签: java arraylist hashmap time-complexity


【解决方案1】:

如图here

import java.io.*; 
import java.util.*; 
  
class GFG{ 
      
    static int NO_OF_CHARS = 256; 
      
    /* function to check whether two strings 
    are Permutation of each other */
    static boolean arePermutation(char str1[], char str2[]) 
    { 
        // Create 2 count arrays and initialize 
        // all values as 0 
        int count1[] = new int [NO_OF_CHARS]; 
        Arrays.fill(count1, 0); 
        int count2[] = new int [NO_OF_CHARS]; 
        Arrays.fill(count2, 0); 
        int i; 
   
        // For each character in input strings, 
        // increment count in the corresponding 
        // count array 
        for (i = 0; i <str1.length && i < str2.length ; 
                                                 i++) 
        { 
            count1[str1[i]]++; 
            count2[str2[i]]++; 
        } 
   
        // If both strings are of different length. 
        // Removing this condition will make the program  
        // fail for strings like "aaca" and "aca" 
        if (str1.length != str2.length) 
            return false; 
   
        // Compare count arrays 
        for (i = 0; i < NO_OF_CHARS; i++) 
            if (count1[i] != count2[i]) 
                return false; 
   
        return true; 
    } 
   
    /* Driver program to test to print printDups*/
    public static void main(String args[]) 
    { 
        char str1[] = ("geeksforgeeks").toCharArray(); 
        char str2[] = ("forgeeksgeeks").toCharArray(); 
          
        if ( arePermutation(str1, str2) ) 
            System.out.println("Yes"); 
        else
            System.out.println("No"); 
    } 
} 
  
// This code is contributed by Nikita Tiwari. 

如果你执着于你的实现,使用 HashSet,它仍然有 O(1) 的查找时间,只是没有键

【讨论】:

    【解决方案2】:

    你可以使用HashSet,因为你只需要一个参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-17
      • 2017-09-12
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多