[英]Java collections vs manual loops - Coding challenges/interview best practices
對於編碼挑戰/面試以及優化,根本不使用集合? 例如,檢查以下程序的回文運行時間
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;
}
}
計算出的運行時間如下所示。
AMANAPLANACANALPANAMA
isPalindrome - 7788
YES
isPalindromeUsingSet - 745473
YES
我的幾個問題是:
我學習優化代碼的方法:
背景 :我從事Java編程已有兩年了。 現在正在學習謎題,算法和時間復雜性的編碼,以進行更大的面試!
任何良好的方向表示贊賞。
謝謝
讓我們看一下HashSet.add
實現:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
在內部, HashSet
使用HashMap
。
現在,讓我們看一下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;
}
我們可以注意到,在計算上,將注冊表放入地圖中是一項“艱巨的任務”。 有一個:
for
循環 因此,如果執行時間是您所關心的問題,那么手動循環比Java Collections是更好的選擇。
現在,就可讀性和可維護性而言,Collections是最佳選擇。
了解比較后關閉,使用了兩個函數是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.