简体   繁体   中英

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?
  2. For coding better optimized solutions, should I look for one loop execution, use a lot of O(1) data structures?

My approach in learning optmization code:

  1. For each coding problem, solve my crude way of java and data structures.
  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. 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:

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

Internally, HashSet uses a HashMap .

Now, let's take a look at the HashMap.put method implementation:

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
  • 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.

Now, in terms of readability and maintainability, Collections is the best choice.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM