package com. mjm. demo. codePractice;
import java. util. ArrayList;
import java. util. Arrays;
import java. util. HashMap;
import java. util. Map;
public class SumOfTwoNums {
public static void main ( String[ ] args) {
int [ ] nums = new int [ ] { 2 , 7 , 11 , 1 , 7 , 3 , 6 } ;
int target = 9 ;
new MyMap ( ) . towSum ( nums, target) ;
System. out. println ( "------" ) ;
new MyMap ( ) . towSumNew ( nums, target) ;
System. out. println ( "------" ) ;
allPrint ( nums, target) ;
}
static void allPrint ( int [ ] nums, int target) {
for ( int i = 0 ; i < nums. length; i++ ) {
int num = target - nums[ i] ;
if ( num > 0 ) {
for ( int j = i + 1 ; j < nums. length; j++ ) {
if ( nums[ j] == num) {
System. out. println ( Arrays. toString ( new int [ ] { i, j} ) ) ;
}
}
}
}
}
static void putMap ( int [ ] nums, int target) {
MyHashMap< Integer, Integer> myHashMap = new MyHashMap < > ( ) ;
for ( int i = 0 ; i < nums. length; i++ ) {
int num = target - nums[ i] ;
if ( num > 0 ) {
for ( int j = i + 1 ; j < nums. length; j++ ) {
if ( nums[ j] == num) {
myHashMap. put ( i, j) ;
}
}
}
}
myPrint ( myHashMap) ;
}
static void putMap2 ( int [ ] nums, int target) {
HashMap< Integer, Integer> map = new HashMap < > ( 16 ) ;
for ( int i = 0 ; i < nums. length; i++ ) {
int num = target - nums[ i] ;
if ( num > 0 ) {
for ( int j = i + 1 ; j < nums. length; j++ ) {
if ( nums[ j] == num) {
map. put ( i, j) ;
}
}
}
}
myPrint ( map) ;
}
static class MyMap {
public void towSum ( int [ ] nums, int target) {
putMap ( nums, target) ;
}
public void towSumNew ( int [ ] nums, int target) {
putMap2 ( nums, target) ;
}
}
static void myPrint ( HashMap< Integer, Integer> myHashMap) {
for ( Map. Entry< Integer, Integer> entry : myHashMap. entrySet ( ) ) {
String str = "[" + entry. getKey ( ) + "," + entry. getValue ( ) + "]" ;
ArrayList< String> list = new ArrayList < > ( ) ;
list. add ( str) ;
for ( String s : list) {
System. out. println ( s) ;
}
}
}
}
class MyHashMap < K, V> extends HashMap < K, V> {
@Override
public V put ( K key, V value) {
if ( ! containsKey ( key) ) {
return super . put ( key, value) ;
}
return null;
}
}
输出
[ 0,1]
[ 5,6]
------
[ 0,4]
[ 5,6]
------
[ 0, 1]
[ 0, 4]
[ 5, 6]
Process finished with exit code 0