210918 토 Algorithms TIL

bongf·2021년 9월 18일
0

알고리즘TIL

목록 보기
2/153

https://bong-f.tistory.com/256

오픈채팅방

문자열 압축

문제풀이

  • 리스트의 인덱스 0, 1 / 1, 2 / 2,3 이런 식으로 쭉쭉쭉 비교해줘야 한다고 했을 때
  • 파이썬은 리스트를 복사해서 두번쨰 리스트의 첫번째 요소를 제거하고 마지막에 ''를 붙여서 길이를 맞춰준 다음
  • 두 리스트의 같은 인덱스의 값을 비교하는 방법을 썼고
  • 자바는 재귀함수를 썼다. 어쨌든 그 리스트가 String을 리스트로 만들어서 비교하는 리스트였는데, 리스트로 바꾸지 않고 substring을 썼다. String의 subString으로 자르면서 String을 갱신해줬고 그 갱신한 String을 재귀함수에 새로 넣어주면서 substring으로 비교할 값을 갱신했다.

Java

리스트 복사

(1) ArrayList 이용한 복사는 얕은 복사

List<String> a = new ArrayList(복사하려는리스트); 

(2) Collections.copy(), addAll() 모두 얕은 복사. 깊은 복사 하려면 구현해줘야 한다.

리스트 인덱스로 삭제

  • del
  • 리스트 인덱스 제거

배열 복사

  • array copy

Arrays copy

 private static void useArraysClass1() {
        int[] arr1 = { 1, 2, 3};
        int[] copiedArr1 = Arrays.copyOf(arr1, 5);
        int[] copiedArr2 = Arrays.copyOf(arr1, 2);
        System.out.println(Arrays.toString(copiedArr1)); // [1, 2, 3, 0, 0]
        System.out.println(Arrays.toString(copiedArr2)); //[1, 2]
    }
 
 
 private static void useArraysClass2() {
        int[] arr = { 1, 2, 3, 4, 5};
        int[] copied1 = Arrays.copyOfRange(arr, 1, 3); // [2, 3]
        int[] copied2 = Arrays.copyOfRange(arr, 1, 10); // [2, 3, 4, 5, 0, 0, 0, 0, 0]
        System.out.println(Arrays.toString(copied1));
        System.out.println(Arrays.toString(copied2));
    }
 

System array copy

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html

public static void arraycopy(Object src,
             int srcPos,
             Object dest,
             int destPos,
             int length)

  private static void useSystemClass() {
        int[] arr1 = { 1, 2, 3};
        int[] arr2 = { 4, 5};
        int[] arrResult = new int[5];
        System.arraycopy(arr1, 0, arrResult, 0, 2);
        System.out.println(Arrays.toString(arrResult)); // [1, 2, 0, 0, 0]
        System.arraycopy(arr2, 0, arrResult, 1, 2);
        System.out.println(Arrays.toString(arrResult)); // [1, 4, 5, 0, 0]
    }
profile
spring, java학습

0개의 댓글