简体   繁体   English

Java集合与手动循环-编码挑战/面试最佳实践

[英]Java collections vs manual loops - Coding challenges/interview best practices

For coding challenges/interview as well as optimization, is it good to use collections at all? 对于编码挑战/面试以及优化,根本不使用集合? For example, check the palindrome running time for below program 例如,检查以下程序的回文运行时间

    import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Palindrome {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        if(isPalindrome(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

        if(isPalindromeUsingSet(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

    }

    public static boolean isPalindrome(String str) {
        final long startTime = System.nanoTime();
        final long duration;
        for (int i=0;i<str.length()/2;i++) {
            if(str.charAt(i) != str.charAt(str.length() -1 -i)) {
                duration = System.nanoTime() - startTime; 
                System.out.println("isPalindrome - " + duration);
                return false;
            } 
        }
        duration = System.nanoTime() - startTime; 
        System.out.println("isPalindrome - " + duration);

        return true;
    }

    public static boolean isPalindromeUsingSet(String str) {
    final long startTime = System.nanoTime();
    final long duration;
    Set<Character> charSet = new HashSet<>();
    for (int i=0;i<str.length()/2;i++) {
        if(charSet.add(str.charAt(i)) == false) {
            duration = System.nanoTime() - startTime; 
            System.out.println("isPalindromeUsingSet - " + duration);
            return false;
        } else {
            charSet.remove(str.charAt(i));
        }
    }
    duration = System.nanoTime() - startTime; 
    System.out.println("isPalindromeUsingSet - " + duration);
    return true;
}

}

Running Time as calculated is shown below. 计算出的运行时间如下所示。

AMANAPLANACANALPANAMA
isPalindrome - 7788
YES
isPalindromeUsingSet - 745473
YES

My couple of questions are: 我的几个问题是:

  1. So java collections are mostly safe and versatile in various CRUD operations, why not use them? 因此,java集合在各种CRUD操作中大部分都是安全且通用的,为什么不使用它们呢?
  2. For coding better optimized solutions, should I look for one loop execution, use a lot of O(1) data structures? 为了编码更好的优化解决方案,我是否应该寻找一个循环执行,使用大量O(1)数据结构?

My approach in learning optmization code: 我学习优化代码的方法:

  1. For each coding problem, solve my crude way of java and data structures. 对于每个编码问题,请解决我的Java和数据结构的粗略方法。
  2. Go and study the best solution later, calculate time and complexity and adapt in my solutions gradually. 以后去研究最佳解决方案,计算时间和复杂度,并逐步适应我的解决方案。

Background : I've been coding java for couple of years. 背景 :我从事Java编程已有两年了。 Now learning coding for puzzles, algorithms and time complexity for acing bigger interviews! 现在正在学习谜题,算法和时间复杂性的编码,以进行更大的面试!

Any good direction is appreciated. 任何良好的方向表示赞赏。

Thanks 谢谢

Let's take a look at the HashSet.add implementation: 让我们看一下HashSet.add实现:

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

Internally, HashSet uses a HashMap . 在内部, HashSet使用HashMap

Now, let's take a look at the HashMap.put method implementation: 现在,让我们看一下HashMap.put方法的实现:

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

We can notice that puting a registry into the map it's a "hard task", computationally speaking. 我们可以注意到,在计算上,将注册表放入地图中是一项“艰巨的任务”。 There is a: 有一个:

  • hash algorithm 哈希算法
  • for loop for循环
  • add entry method execution 添加入口方法执行
  • and so on... 等等...

So, if execution time it's a concern in your scenario, manual loops it's a better choice than Java Collections. 因此,如果执行时间是您所关心的问题,那么手动循环比Java Collections是更好的选择。

Now, in terms of readability and maintainability, Collections is the best choice. 现在,就可读性和可维护性而言,Collections是最佳选择。

了解比较后关闭,使用了两个函数是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 采访编码Java排序 - Interview Coding Java Sorting 对不同Java集合进行基准测试的最佳实践是什么? - What are the best practices for benchmarking different Java collections? 使用字符串,变量,循环的正确编码实践-Java(Android) - Correct coding practices with strings, variables, loops - Java (Android) Java编码标准/最佳实践 - 中断/继续标签的命名约定 - Java Coding standard / best practices - naming convention for break/continue labels 循环中的条件,最佳实践? - Conditions in loops, best practices? 重用查询的一部分进行计数的Java编码最佳实践 - Java coding best-practices for reusing part of a query to count 在用于分发的 java 应用程序中编码文件路径的最佳做法是什么? - What are best practices for coding filepaths in java applications intended for distribution? 需要有关编码最佳实践的建议 - Advice needed on coding best practices Java最佳实践 - 返回对象与通用 - Java Best Practices - Returning an Object vs. a Generic 终端输出到变量(从Java到python)-将输出放入RAM而不是写入文件的最佳编码实践 - terminal output to variable (from java to python) - Best coding practices for placing output into RAM instead of writing files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM