Find Anagrams Mapping

Map ๋ชจ๋ฅธ๋‹ค๊ณ  ๊ฒ๋จน์ง€ ๋ง๊ธฐ. Map์œผ๋กœ ํ‘ธ๋Š” ๋ฌธ์ œ ์น˜๊ณ ๋Š” ์‰ฌ์šด ๋ฌธ์ œ!

Example Input : int[ ] A = {11,27,45,31,50}; int[ ] B = {50,11,31,45,27}; Output : [1 4 3 2 0]

์ž๋ฃŒ๊ตฌ์กฐ : Map ์ด์šฉ

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ๋‹ด์„ ๊ทธ๋ฆ‡ ์ƒ์„ฑ : Map๊ณผ ์ •๋‹ต ๋ฐฐ์—ด 2. Map์— B๋ฐฐ์—ด์„ ๋‹ด๋Š”๋‹ค. (key,value) = (B[i],i). ์™œ๋ƒํ•˜๋ฉด ์ฐพ๊ณ ์žํ•˜๋Š” ๊ฒƒ์€ ์›์†Œ๊ฐ’์ด๊ณ , ์›์†Œ๊ฐ’์ด ๋ช‡๋ฒˆ์งธ ์ธ๋ฑ์Šค์ธ์ง€(value)๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด! 3. Map์—์„œ A์˜ ์›์†Œ๊ฐ€ ๋ช‡๋ฒˆ์งธ์ธ์ง€๋ฅผ ์ •๋‹ต ๋ฐฐ์—ด์— ๋„ฃ๋Š”๋‹ค. ์ •๋‹ต ๋ฐฐ์—ด์„ ๋ฆฌํ„ดํ•œ๋‹ค.

public static void main(String[] args) {
			int[] A = {12, 28, 46, 32, 50};
			int[] B = {50, 12, 32, 46, 28};
			int [] result = anagramMappings(A, B);
			print(result);
		}
		
		public static void print(int[] result) {
			for(int i=0; i< result.length; i++) {
				System.out.print(result[i]+" ");
			}
		}

		public static int[] anagramMappings(int[] A, int[] B) {
		    int leng = A.length;
		    int[] res = new int[leng];
        HashMap<Integer,Integer> map = new HashMap<>();
		    for(int i=0;i<leng;i++){
		        map.put(B[i],i);
		    }
		    for(int i=0;i<leng;i++){
		        res[i] = map.get(A[i]);
		    }        
		    return res;
		}

Last updated