20220513 TIL

Don Lee·2022년 5월 14일
0

EpiTIL

목록 보기
5/24
  • 20220513
    • 공간 복잡도
      • 공간 복잡도는 시간 복잡도의 중요성보다는 크게 낮다. 공간 복잡도를 희생할지라도 시간 복잡도를 낮춰야한다.
      • 대부분의 문제에서는 알고리즘의 성능이 공간에 의해서 결정되지 않습니다. 따라서 공간 복잡도보다는 시간 복잡도를 더 신경 써야 합니다.
      • 코딩 연습

직사각형 별찍기

https://programmers.co.kr/learn/courses/30/lessons/12969

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        String star = "";
        for (int i = 0; i < a; i++) {
            star += "*";
        }
        for (int i = 0; i < b; i++) {
            System.out.println(star);
        }
        System.out.println(a + b);
    }
}

이중 for문을 돌리는 것 보다 다른 for문 두 개 돌리는 것이 시간 복잡도를 낮춤으로 이렇게 짬. 단, 별 개수가 row마다 다를 경우 위의 코드가 적용이 불가.

짝수와 활수

https://programmers.co.kr/learn/courses/30/lessons/12937

class Solution {
  public String solution(int num) {
 
		if(num %2 == 0) {
			return ("Even");
		} else
			return ("Odd");
  }
}

가운데 글자 가져오기

https://programmers.co.kr/learn/courses/30/lessons/12903

public class Main {
    public static void main(String[] args) {
        String answer = "qwer";

        int length_of_answer = answer.length();

        if (length_of_answer % 2 == 0) {
            System.out.print(answer.charAt(length_of_answer / 2 - 1));
            System.out.println(answer.charAt(length_of_answer / 2));
        } else{
            System.out.print(answer.charAt(length_of_answer / 2));
        }
    }
}
/Library/Java/JavaVirtualMachines/jdk-18.0.1.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=57289:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/lee/IdeaProjects/untitled6/out/production/untitled6 Main
we

Process finished with exit code 0
public class Main {
    public static void main(String[] args) {
        String answer = "abcde";

        int length_of_answer = answer.length();

        if (length_of_answer % 2 == 0) {
            System.out.print(answer.charAt(length_of_answer / 2 - 1));
            System.out.println(answer.charAt(length_of_answer / 2));
        } else{
            System.out.print(answer.charAt(length_of_answer / 2));
        }
    }
}
/Library/Java/JavaVirtualMachines/jdk-18.0.1.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=57335:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/lee/IdeaProjects/untitled6/out/production/untitled6 Main
c
Process finished with exit code 0

이렇게 하면 잘 출력된다. 다만 인수 s를 고려하면 아래와 같은 코드로 다시 짜야한다.

처음에는 charAtsubstring으로 바꾸었지만 제대로 동작하지 않았다.

Screen Shot 2022-05-13 at 3.18.27 PM.png

class Solution {
    public String solution(String s) {
        String answer = "";

        if(s.length()%2==0) {
            answer = s.substring(s.length()/2-1, s.length()/2+1);
        } else {
            answer = s.substring(s.length()/2,s.length()/2+1);
        }

        return answer;
    }
}

답안으로 제출할 때는 위의 코드로 제출해야한다.

Screen Shot 2022-05-13 at 3.53.04 PM.png

두 정수 사이의 합

https://programmers.co.kr/learn/courses/30/lessons/12912

public class Main {
    public static void main(String[] args) {
        Solution answer = new Solution();

        System.out.println(answer.solution(3,5));
    }
}

class Solution {
    public long solution(int a, int b) {
        long answer = 0;

        if (a <= b) {
            for (int i = a; i <= b; i++) {
                answer += i;
            }
        } else {
            for (int i = b; i <= a; i++) {
                answer += i;
            }
        }
        return answer;
    }
}

// b가 a보다 큰 수면 a를 c만큼 1씩 더하면서 증가하고 b를 더하면 종료
// a가 b보다 큰 수면 b를 c만큼 1씩 더하면서 증가하고 a를 더하면 종료

인텔리제이 내부에서 문제를 돌리는 방법을 깨달음.

문자열을 정수로 바꾸기

https://programmers.co.kr/learn/courses/30/lessons/12925

public class Main {
    public static void main(String[] args) {
        Solution answer = new Solution();

        System.out.println(answer.solution("1234"));
    }
}

class Solution {
    public int solution(String s) {
        int answer = 0;

        answer = Integer.parseInt(s);

        return answer;
    }
}

없는 숫자 더하기

https://programmers.co.kr/learn/courses/30/lessons/86051

class Solution {
    public int solution(int[] numbers) {
        int num = 45;

        for (int i = 0; i < numbers.length; i++) {
            num -= numbers[i];
        }
        return num;
    }
}
//0부터 9까지 더 한 모든 숫자에서 리스트의 숫자 하나씩 빼면 되지 않을까? <- 맞음

음양 더하기

https://programmers.co.kr/learn/courses/30/lessons/76501

class Solution {
    public int solution(int[] absolutes, boolean[] signs) {
        int num = 0;
        boolean a = true;

        for (int i = 0; i < absolutes.length; i++) {
            if (signs[i] = a) {
                absolutes[i] = Math.abs(absolutes[i]);
            } else {
                absolutes[i] = (Math.abs(absolutes[i]) * -1 );
            }
            num += absolutes[i];
        }
        return num;
    }
}

// absolutes(이후 a)와 signs(이후 s)를 받음
// s가 true이면 a는 양수, s가 false이면 a는 음수로 바꿈. 그렇게 모든 수를 하나씩 꺼냄.
// 마지막으로 s의 모든 수를 더함.

else 부분에서 * -1을 해서 음수로 될 줄 않았는데 안 됨. 문제는 boolean a = true;

왜 그럴까?

💡 해당 부분 왜 그런지 확인해볼 것
class Solution {
    public int solution(int[] absolutes, boolean[] signs) {
        int num = 0;

        for (int i = 0; i < absolutes.length; i++) {
            if (signs[i]) {
                absolutes[i] = Math.abs(absolutes[i]);
            } else {
                absolutes[i] = (Math.abs(absolutes[i]) * -1 );
            }
            num += absolutes[i];
        }
        return num;
    }
}

제거하면 잘 나옴.

평균 구하기

https://programmers.co.kr/learn/courses/30/lessons/12944

class Solution {
    public double solution(int[] arr) {
        double answer = 0;
        for (int i = 0; i < arr.length; i++) {
            answer += arr[i];   
        }
        answer = answer / arr.length;
        return answer;
    }
}

핸드폰 번호 가리기

https://programmers.co.kr/learn/courses/30/lessons/12948

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.solution("01033334444"));
    }
}

class Solution {
    public String solution(String phone_number) {
        String answer = "";
        for (int i = 0; i < phone_number.length(); i++) {
            if (i < phone_number.length() - 4) {
                answer += "*";
            } else {
                answer += phone_number.charAt(i);
            }
        }
        return answer;
    }
}
// 전화번호의 길이를 알아야 한다.
// 전화번호의 길이, 예를들어 11이라는 것이 나오면, 1부터 7까지는 공란에 별을 더한다.
// 그 이후에는 일반 숫자들을 별이 채워진 문자열에 더한다.

answer += phone_number.charAt(i); 에서 charAt(i) 부분을 빼먹어 좀 고생했다. 결국 구글링으로 해결

[JAVA] 배열 출력하기(toString, deepToString)

https://seongsillvanas.tistory.com/9

행열을 좀 더 공부해야겠다. 내가 모르는 부분

class Solution {
    public String solution(String phone_number) {
        char[] ch = phone_number.toCharArray();
        for(int i = 0; i < ch.length - 4; i ++){
            ch[i] = '*';
        }
        return String.valueOf(ch);
    }
}

// 다른 사람이 제출한 것을 보니 toCharArray를 통해 간단하게 구현.

toCharArray에 관한 설명 → https://yadon079.github.io/2020/java/tochararray

profile
쾌락코딩

0개의 댓글