問題:整数の配列を考えると、2つの数のどのと指定された値を返す2つの数の添え字にそれを作るを見つけます。変化配列要素の値を仮定し、時間計算量はO(N)のために必要な、N配列の長さです。
アイデア:それスキャンアレイ再度、キー<値、インデックス>メモリハッシュテーブル、再び現在の走査対象とハッシュテーブルの差か。
達成のJava:
int[] twoSum(int[] A,int target){
int[] res={-1,-1};
if(A==null||A.length<2)
return res;
HashMap<Integer,Integer> ihm=new HashMap<Integer,Integer>();
for(int i=0;i<A.length;i++){
ihm.put(A[i],i);
}
for(int i=0;i<A.length;i++){
if(ihm.containsKey(target-A[i])&&target!=2*A[i]){
res[0]=i;
res[1]=ihm.get(target-A[i]);
break;
}
}
return res;
}