두개의 문자열을 입력받은 후 , 각각의 문자열 속에 중복되는 문자가 존재하면 YES출력 아니면 NO를 출력하는 문제이다.

 

- 풀이방법

문자열을 char배열로 변환하여 map에 넣은 후, key값이 존재하면 YES를 출력 아니면 NO를 출력하도록 했다.

 

static String twoStrings(String s1, String s2) {
    int result = 0;
    HashMap<String, Integer> map = new HashMap<String, Integer>();
        
    for(char c : s1.toCharArray()){
        if(!map.containsKey(""+c)){
            map.put(""+c, 1);
        }
    }

    for(char c : s2.toCharArray()){
        if(map.containsKey(""+c)){
            result++;
        }
    }

    return (result == 0) ? "NO" : "YES";
}

 

 

유일하게 번역기 안돌리고 그냥 풀리다니.. 반갑구나 반가워요~~

 

두 개의 String 배열을 인자로 받는데, 

첫번째 String 배열 안에 두번째 String 배열 내의 모든 요소들이 존재하면 Yes를 출력, 아니면 No를 출력하는 문제이다.

 

풀이 방법은

hashMap을 이용해서 일단 첫번째 String 배열 내의 모든 요소들을 key로 해서 집어 넣는다.

value는 1로 넣으면서, 중복 문자가 있다면 value의 숫자를 1씩 증가시키면서 넣어주었다.

 

그리고, 두번째 String 배열 내의 모든 요소들을 루프로 돌면서 map안에 key가 존재하는지, 존재하면 value를 1씩 차감시켰고, 존재하지 않거나 value가 0보다 작아지는 경우 No를 출력하도록 했다.

 

static void checkMagazine(String[] magazine, String[] note) {
    // 1. 잡지에 나오는 문자열에 note의 문자열이  모두 포함되어있으면 YES else No 출력
        
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    for(int i=0; i<magazine.length; i++){
       if(!map.containsKey(magazine[i])){
           map.put(magazine[i], 1);
       }else{
           map.put(magazine[i], map.get(magazine[i])+1);
       }
    }

        
    for(int i=0; i<note.length; i++){
        if(!map.containsKey(note[i])){
            System.out.println("No");
            return;
        }else{
            if(map.get(note[i]) > 0){
                map.put(note[i], map.get(note[i])-1);
            }else{
                System.out.println("No");
                return;
            }
        }
    }
    System.out.println("Yes");
    return;
}

 

 

 

정수형 배열이 주어지면, 중복되지 않는 쌍(pair)을 만들어

각 쌍에서 원소들 간의 차이 값에 대한 절대값이 가장 최소인 값이 얼마인지 반환하는 문제이다. 

 

 

간단한 문제라 아래와 같이 풀이 후 Submit을 눌렀는데...

static int minimumAbsoluteDifference(int[] arr) {
    int min = Integer.MAX_VALUE;

    for(int i=0; i<arr.length-1; i++){
        for(int j=i+1; j<arr.length; j++){
            min = Math.min(min, Math.abs(arr[i]-arr[j]));
        }
    }
    return min;
}

 

두 개의 Test Case에서 Fail이 났고, Fail 사유는 시간초과. 

 

이중 for문으로 시간복잡도가 O(n^2)이다.

 

그래서 한번의 for문을 이용해 풀어야한다.. 

정렬 후에 인접한 값을 빼주는 방법을 이용하면 한번의 for문으로 가능.

static int minimumAbsoluteDifference(int[] arr) {
    int min = Integer.MAX_VALUE;

    Arrays.sort(arr);

    for(int i=0; i<arr.length-1; i++){
        min = Math.min(min, Math.min(min, Math.abs(arr[i]-arr[i+1])));
    }
    return min;
}

 

문자열과 숫자를 순서대로 입력받아,

문자열의 길이가 두번째 인자로 받은 숫자만큼 길이가 될때 까지 문자열을 붙인후, 

'a'문자의 갯수를 파악하는 문제이다. 

 

단순히 생각하고 접근하면 테스트케이스에서 두번째 숫자가 커질경우, OutOfMemory 에러가 발생한다..

 

 

static long repeatedString(String s, long n) {
     long multipleNum =0;
     int aCnt = 0;
     long result = 0 ;

	 //먼저 문자열에서 a개수를 세고,
     //문자열을 붙인 수 만큼 곱해서 몫을 구한다.
     for(int i=0; i<s.length(); i++){
         if('a' == s.charAt(i))
             aCnt++;
     }

     multipleNum = n/s.length();
     result =  aCnt*multipleNum;

	 //나머지 문자열에서 a의 개수를 구해서 더한다.
     long remainder = n%s.length();

     for(int i=0; i<remainder; i++){
         if('a' ==s.charAt(i))
             result++;
     }
     return result;
}

 

 

배열이 주어지면 0 으로만 점프할 수 있으며, 최대 i+2인덱스 씩 점프가 가능하다. 

만약 i+2번째 인덱스의 숫자가 1이라면 i+1번째 인덱스로 점프해야 한다.

 

배열의 마지막 인덱스까지의 최소 점프 횟수를 구하는 문제.

static int jumpingOnClouds(int[] c) {
	int jumping = 0;
	int i = 0;

	try{
		while(true){
			if(i+1 >= c.length) break;

			if(c[i+2] == 0){
				jumping++;
				i+=2;
			}else{
				jumping++;
				i++;
			}
		}
	}catch(java.lang.ArrayIndexOutOfBoundsException e){
		jumping++;
	}

	return jumping;
}

 

 

편법이다.. 

ArrayIndexOutOfBoundsException이 발생하는 Case가 있기때문에 해당 Exception발생시, 점프횟수를 +1 해주었다.

검색좀 해보니 동적계획법을 이용해 푸는방법이 있는데, 다음번에 포스팅해야겠다..

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are  socks with colors . There is one pair of color  and one of color . There are three odd socks left, one of each color. The number of pairs is .

 

Sample Input

9

10 20 20 10 10 30 50 10 20

Sample Output

3

 

 

배열안에 숫자들이 들어오는데 양말처럼 짝을 지어서 몇 짝이 나오는지 반환하는 문제이다.

 

 

static int sockMerchant(int n, int[] ar) {
	int result = 0;
	HashSet<Integer> colors = new HashSet<Integer>();

	for(int i = 0; i < ar.length ; i++){
		if(!colors.contains(ar[i])){
			colors.add(ar[i]);
		}else{
			result++;
			colors.remove(ar[i]);
		}
	}
	return result;
}

HashSet에 하나씩 담으면서 중복데이터가 있을경우 수량을 ++ 하고, 해당 요소를 제거하는 방법이다. 

시간복잡도 O(1)

- 자바 [getOrDefault, putIfAbsent]

 

1. getOrDefault

map.getOrDefault(key, defaultValue)

map에서 key 를 찾아 있으면 key의 value를 반환하고, 없으면 defaultValue 를 반환


2.putIfAbsent

 

map.putIfAbsent(key, value)

map에 key가 없으면 데이터 셋을 넣고[map.put(key, value)], map에 key가 있으면 건너띈다.

 

개발을 할 떄 가장 많이 쓰이는 기능 중에 하나는 아마도 랜덤 숫자를 구하는 작업 일 것이다.
예전에는 Math.random()을 많이 이용하였으나, 요즘은 Random클래스를 많이 이용한다.


- Math.random()과 Random 클래스의 차이

> Math.Random()

Random()메소드는 return 타입이 double형으로, double 타입의 임의의 수를 발생한다.
가이드를 보면 static이고, 변환 타입이 double인 것을 확인할 수 있다.

 

Random()메소드는 static으로 선언되었기 때문에 위와 같이 객체 생성 절차 없이
double d = Math.random();
바로 Math의 Random()메소드를 실행시킴으로써 랜덤 숫자를 구할 수 있다.

하지만, return 타입이 double형 이기 때문에 결과는 0.xxx... 과 같은 소수값으로 반환된다.
따라서 결과값에 '*10 '(곱하기 10) 을 해주는 작업이 필요하다.


double d = Math.random();
System.out.println(d);

int di = (int)(d*10);
System.out.println(di);

다음과 같이 결과에 10을 곱해주고, int형으로 명시적 형변환을 해준다음 사용해야 한다.


결과: 
0.59656663..(랜덤값)
5

 


> Random 클래스

Random 클래스는 많이 쓰이는 클래스이고 return 타입이 int이므로 사용법이 아주 간단하다.

Random클래스는 Math 클래스와 다르게 직접 new생성자를 이용하여 객체생성 후 사용한다.
또한 return 타입이 int이다.

위 이미지를 보면 Random클래스의 nextInt메소드는 int형으로 bound값을 파라미터로 받는다.
따라서, random.nextInt(100);  을 실행시키면
1부터 100이하의 정수를 return 해준다.


Random random = new Random();
int i = random.nextInt(100);
System.out.println(i);

결과:
42(랜덤값)

 

 


- Scanner 클래스

키보드에서 타이핑하는 문자열 또는 입출력 프로그래밍에서 문자열을 읽어올때 사용된다.

Scanner scanner new Scanner(System.in);

다음은 선언부이다.
new생성자를 이용해 Scanner 객체를 생성해주면서 매개변수로 "System.in"을 넣어주어야 한다.

int i = scanner.nextInt();            //정수를 입력받는다.
String str = scanner.next();        //문자열을 입력받는다.
String strln = scanner.nextLine();  //'개행문자(\n)'를 만나기 전까지 문자열을 입력받는다.

 

 


- Wrapper 클래스

Wrapper클래스는 기초데이터를 객체데이터로 변화시키는 클래스이다. 

 


Integer integer = new Integer(10);

int i = 10;

 

위 두줄은 결과적으로 같은 코드이지만 위에는 객체(Object)자료형이고 밑에는 기초자료형이다.
위 이미지를 보면 객체자료형을 기초자료형으로 변환시켜 넣어주기위해 
return 타입이 int인 integer.intValue()메소드를 이용하는 것도 확인할 수 있다.

 

 

 

+ Recent posts