Problem Solving with Algorithms

반응형

Introduction to Data Structure


Overview

Introduction

 

Arrays are a simple data structure for storing lots of similar items. They exist in all programming languages, and are used as the basis for most other data structures. On their own, Arrays can be used to solve many interesting problems. Arrays come up very often in interview problems, and so being a guru with them is a must!

In this Explore Card, we'll introduce Arrays and solve some cool problems with them. This Card is beginner friendly, and we've provided lots of code snippets in Java to help you understand. Each topic begins with informative articles, followed by real interview problems for you to practice on.

In addition, the problems have hints which will help you in building up ideas on how to solve them. These hints will be subtle enough to set you on a particular path for reaching the optimized solution, without giving away the answer too easily.

After completing this Explore Card on Arrays, you will understand:

  • What an Array is.
  • Basic properties of Arrays.
  • Implementing basic Array operations.
  • Simple programming techniques with Arrays.

Before you start, bear in mind that should you have any questions or comments, you can always post them in the Discussion forum that is located at the end of the card. We'll do our best to respond to you as soon as we can.

 

소개
배열은 유사한 항목을 많이 저장하기위한 간단한 데이터 구조입니다. 모든 프로그래밍 언어에 존재하며 대부분의 다른 데이터 구조의 기초로 사용됩니다. 그 자체로 배열을 사용하여 많은 흥미로운 문제를 해결할 수 있습니다. 배열은 인터뷰 문제에서 자주 등장하므로 전문가가되는 것은 필수입니다!

이 탐색 카드에서는 어레이를 소개하고 몇 가지 멋진 문제를 해결할 것입니다. 이 카드는 초보자에게 친숙하며 이해를 돕기 위해 Java로 많은 코드 스 니펫을 제공했습니다. 각 주제는 유익한 기사로 시작하여 연습 할 실제 인터뷰 문제가 이어집니다.

또한 문제에는 문제 해결 방법에 대한 아이디어를 구축하는 데 도움이되는 힌트가 있습니다. 이러한 힌트는 너무 쉽게 답을주지 않으면 서 최적화 된 솔루션에 도달하기위한 특정 경로를 설정하기에 충분히 미묘합니다.

어레이에서이 탐색 카드를 완료하면 다음을 이해할 수 있습니다.

배열이란 무엇입니까?
배열의 기본 속성.
기본 배열 작업을 구현합니다.
배열을 사용한 간단한 프로그래밍 기술.
시작하기 전에 질문이나 의견이있는 경우 카드 끝에있는 토론 포럼에 언제든지 게시 할 수 있습니다. 최대한 빨리 답변을 드리기 위해 최선을 다하겠습니다.

 


Introduction

In this chapter, we'll begin by looking at what an Array is, and what it's used for. We'll start by comparing Arrays to a real-world problem: storing lots of DVDs in an organized way. After that, we'll look at how to create and work with Arrays in Java.

 

소개
이 장에서는 배열이 무엇이며 용도가 무엇인지 살펴 보겠습니다. 어레이를 실제 문제와 비교하는 것으로 시작하겠습니다. 많은 DVD를 체계적으로 저장하는 것입니다. 그런 다음 Java에서 배열을 만들고 사용하는 방법을 살펴 보겠습니다.

 


Array - A DVD box?


Suppose you had a bunch of DVDs at home that you wanted to arrange neatly. What would be the ideal choice for storing such a thing? You could find a cardboard box (or some other box) big enough to arrange all of the DVDs neatly, right? It's as simple as that. However, you might want to add a new DVD to the box, or you might want to get rid of the old ones that you've watched a million times over in the past. An important consideration for this box would be that you would only place DVDs in it and nothing else; you wouldn't place your clothes in it, for example. The box would contain multiple items, but all of them would be of the same type. In this case, that type is DVD. Items of the same type share properties. For DVDs, those properties include:

  • All the DVDs would be inside a plastic cover.
  • The cover would have the name of the movie, the cast, and all sorts of other details.
  • All the covers would be of exactly the same size and would contain just one, and only one, DVD.

You might not actually name the DVD box, but when you want your sister to fetch a DVD, you'd tell her that the DVD is inside your "DVD box", and she would instantly know where to find the box. This is a very simple yet realistic scenario that is easy to understand and relate to. So, now let us move over to the world of computers and port this example to programming.

Suppose you were told that you needed to build some software to keep track of all the DVDs in an inventory. This is the exact same scenario that we just described above, but on a much larger scale. So let's imagine the DVD box as a virtual DVD library. For each DVD, you would have certain properties that would be specific attributes of the movies themselves.

In addition to the properties of a DVD, you're also told the maximum number of DVDs that can be stored in the inventory. Obviously, you wouldn't want to store ancient movies from the 1900s unless they were popular ones, right? Say you were told that the requirement is to maintain a maximum inventory of just 100 DVDs. This is an important piece of information because, without this, you wouldn't be able to find the perfectly sized box to fit all the DVDs easily. How could we find a box of a particular size that would be able to fit a maximum of 100 DVDs? Well, lucky for us, we don't need to physically find a cardboard box or anything—there's a programming construct for this purpose. That programming construct is known as an Array.

 

 

어레이-DVD 상자?
집에 깔끔하게 정리하고 싶은 DVD가 많이 있다고 가정 해 보겠습니다. 그런 물건을 보관하는 데 이상적인 선택은 무엇입니까? 모든 DVD를 깔끔하게 정리할 수있는 큰 판지 상자 (또는 다른 상자)를 찾을 수 있습니다. 그렇게 간단합니다. 그러나 상자에 새 DVD를 추가하거나 과거에 백만 번 시청 한 오래된 DVD를 제거 할 수 있습니다. 이 상자에 대한 중요한 고려 사항은 DVD 만 넣을 것입니다. 예를 들어 옷을 넣지 않을 것입니다. 상자에는 여러 항목이 포함되지만 모두 동일한 유형입니다. 이 경우 해당 유형은 DVD입니다. 동일한 유형의 항목은 속성을 공유합니다. DVD의 경우 이러한 속성에는 다음이 포함됩니다.

모든 DVD는 플라스틱 덮개 안에 있습니다.
표지에는 영화의 이름, 출연진 및 기타 모든 종류의 세부 정보가 있습니다.
모든 표지는 정확히 같은 크기이고 DVD는 단 하나뿐입니다.
실제로 DVD 상자의 이름을 지정하지 않을 수도 있지만 자매가 DVD를 가져 오길 원할 때 DVD가 "DVD 상자"안에 있다고 말하면 상자를 찾을 수있는 위치를 즉시 알 수 있습니다. 이것은 이해하기 쉽고 관련이있는 매우 간단하면서도 현실적인 시나리오입니다. 이제 컴퓨터의 세계로 넘어 가서이 예제를 프로그래밍에 이식 해 보겠습니다.


인벤토리의 모든 DVD를 추적하기 위해 소프트웨어를 구축해야한다고 들었다고 가정 해 보겠습니다. 이것은 위에서 설명한 것과 똑같은 시나리오이지만 훨씬 더 큰 규모입니다. 따라서 DVD 상자를 가상 DVD 라이브러리로 상상해 봅시다. 각 DVD에 대해 영화 자체의 특정 속성이되는 특정 속성이 있습니다.

DVD의 속성 외에도 인벤토리에 저장할 수있는 최대 DVD 수를 알려줍니다. 당연히 1900 년대의 고대 영화가 인기있는 영화가 아니라면 저장하고 싶지 않을 것입니다. 요구 사항은 최대 100 개의 DVD 재고를 유지하는 것입니다. 이것이 없으면 모든 DVD에 맞는 완벽한 크기의 상자를 쉽게 찾을 수 없기 때문에 이것은 중요한 정보입니다. 최대 100 개의 DVD를 넣을 수있는 특정 크기의 상자를 어떻게 찾을 수 있습니까? 운이 좋게도 우리는 골판지 상자 나 그 어떤 것도 물리적으로 찾을 필요가 없습니다.이 목적을위한 프로그래밍 구조가 있습니다. 이 프로그래밍 구조를 배열이라고합니다.

 

 


What Is an Array?


An Array is a collection of items. The items could be integers, strings, DVDs, games, books—anything really. The items are stored in neighboring (contiguous) memory locations. Because they're stored together, checking through the entire collection of items is straightforward.

So, how can we relate this back to the physical DVDs? Well, do you keep your DVDs all around the house in multiple locations? Hopefully not! Most people keep all of their DVDs right next to one another inside one gigantic box, or perhaps on a bookshelf. We do this so that if we need to find a particular DVD, we can quickly search through all of them without running from room to room.

 

Creating an Array


On a computer, Arrays can hold up to N items. The value of N is decided by you, the programmer, at the time you create the Array. This is the same as when we found a big enough cardboard box for the DVDs. Additionally, you also need to specify the type of item that will be going into the Array.

In Java, we use the following code to create an Array to hold up to 15 DVDs. Note that we've also included a simple definition of a DVD for clarity.

 

어레이 란?
배열은 항목 모음입니다. 항목은 정수, 문자열, DVD, 게임, 책 등 모든 것이 될 수 있습니다. 항목은 인접한 (인접한) 메모리 위치에 저장됩니다. 함께 저장되기 때문에 전체 항목 컬렉션을 확인하는 것은 간단합니다.

그렇다면 이것을 물리적 DVD와 어떻게 연관시킬 수 있습니까? 음, DVD를 집안 곳곳에 여러 장소에 보관하고 있습니까? 바라지 않습니다! 대부분의 사람들은 모든 DVD를 하나의 거대한 상자 안에 나란히 놓거나 책장에 보관합니다. 이렇게하면 특정 DVD를 찾아야하는 경우 방에서 방으로 이동하지 않고도 모든 DVD를 빠르게 검색 할 수 있습니다.



배열 만들기
컴퓨터에서 어레이는 최대 N 개의 항목을 보유 할 수 있습니다. N의 값은 배열을 만들 때 프로그래머가 결정합니다. 이것은 우리가 DVD 용으로 충분히 큰 판지 상자를 발견했을 때와 동일합니다. 또한 배열에 들어갈 항목 유형도 지정해야합니다.

Java에서는 다음 코드를 사용하여 최대 15 개의 DVD를 보관할 수있는 Array를 만듭니다. 명확성을 위해 DVD에 대한 간단한 정의도 포함되어 있습니다.

 

// The actual code for creating an Array to hold DVD's.
DVD[] dvdCollection = new DVD[15];

// A simple definition for a DVD.
public class DVD {
    public String name;
    public int releaseYear;
    public String director;

    public DVD(String name, String releaseYear, String director) {
        this.name = name;
        this.releaseYear = releaseYear;
        this.director = director;
    }

    public String toString() {
        System.out.println(
            this.name + ", directed by " + this.director + ", released in " + this.releaseYear));
    }
}

 

After running the above code, we now have an Array called dvdCollection, with 15 places in it. Each place can hold one DVD. At the start, there are no DVD's in the Array; we'll have to actually put them in.

The Array can only hold up to 15 DVDs. If we get a 16th DVD, we'll need to make a new Array. We'll look at how we deal with running out of space, in the next chapter.

Before we move onto actually putting some DVDs into the Array, though, one thing you might be wondering is why we'd make an Array with only 15 places. Why not just make it hold 1000000 DVDs so that we know for sure we'll always have enough space?

Well, the reason is the same as it is for the physical box of DVDs. Do you really want to find a box that could hold 1000000 DVDs when you currently only have 15 DVDs and, in fact, never expect to own more than 100 of them? Is it even worth getting a box that could hold 100 DVDs right now, when you only expect to get a few new ones each year? It will take up a lot more space in your home in the meantime.

It's exactly the same with the Array, where the space in your home is analogous to memory on the computer. If you make an Array with 1000000 spaces, the computer will reserve memory to hold 1000000 DVDs, even if you only put 15 DVDs into it. That memory can't be used for anything else in the meantime—just like the space in your house that has been taken over by that huge cardboard box!

 

위의 코드를 실행 한 후 dvdCollection이라는 배열이 15 개의 위치에 있습니다. 각 장소는 하나의 DVD를 보관할 수 있습니다. 처음에는 어레이에 DVD가 없습니다. 실제로 넣어야합니다.

어레이에는 최대 15 개의 DVD 만 저장할 수 있습니다. 16 번째 DVD를 받으면 새 어레이를 만들어야합니다. 다음 장에서 공간 부족에 대처하는 방법을 살펴 보겠습니다.

실제로 어레이에 DVD를 몇 개 넣기로 이동하기 전에 궁금한 점은 15 개 장소 만있는 어레이를 만드는 이유입니다. 우리가 항상 충분한 공간을 확보 할 수 있도록 1000000 개의 DVD를 담을 수 있도록 만드십시오.

글쎄, 그 이유는 DVD의 실제 상자와 동일합니다. 현재 DVD가 15 개 밖에없고 실제로 100 개 이상을 소유 할 것으로 예상하지 않는데도 1000000 개의 DVD를 담을 수있는 상자를 찾고 싶습니까? 매년 몇 장의 새 DVD 만받을 것으로 예상되는 지금 당장 100 개의 DVD를 담을 수있는 상자를 구입할 가치가 있습니까? 그 동안 집에서 더 많은 공간을 차지하게됩니다.

가정의 공간이 컴퓨터의 메모리와 유사한 어레이와 똑같습니다. 1000000 개의 공간이있는 어레이를 만들면 DVD 15 개만 넣더라도 컴퓨터는 1000000 개의 DVD를 저장할 메모리를 예약합니다. 그 기억은 그동안 다른 용도로 사용할 수 없습니다. 마치 거대한 판지 상자가 차지한 집의 공간 처럼요!

 

 

 


Accessing Elements in Arrays


The two most primitive Array operations are writing elements into them, and reading elements from them. All other Array operations are built on top of these two primitive operations.

 

Writing Items into an Array


To put a DVD into the Array, we need to decide which of the 15 places we'd like it to go in. Each of the places is identified using a number in the range of 0 to N - 1. The 1st place is 0, the 2nd place is 1, the 3rd place is 2... all the way up to the 15th place, which is 14. We call these numbers that identify each place indexes.

Let's put the DVD for The Avengers into the eighth place of the Array we created above.

 

배열의 요소에 액세스
가장 원시적 인 두 가지 Array 작업은 요소를 여기에 쓰고 요소를 읽는 것입니다. 다른 모든 Array 작업은이 두 가지 기본 작업 위에 구축됩니다.



배열에 항목 쓰기
DVD를 어레이에 넣으려면 15 개 장소 중 어느 장소에 넣을지 결정해야합니다. 각 장소는 0에서 N-1 범위의 숫자를 사용하여 식별됩니다. 1 위는 0입니다. , 2 위는 1, 3 위는 2 ... 15 위까지 14 위입니다. 우리는이 숫자들을 각 장소 인덱스라고 부릅니다.

The Avengers 용 DVD를 위에서 만든 Array의 8 번째 자리에 넣으십시오.

 

 

// Firstly, we need to actually create a DVD object for The Avengers.
DVD avengersDVD = new DVD("The Avengers", 2012, "Joss Whedon");

// Next, we'll put it into the 8th place of the Array. Remember, because we
// started numbering from 0, the index we want is 7.
dvdCollection[7] = avengersDVD;

And that's it. We've put the DVD for The Avengers into our Array! Let's put a few more DVD's in.

 

DVD incrediblesDVD = new DVD("The Incredibles", 2004, "Brad Bird");
DVD findingDoryDVD = new DVD("Finding Dory", 2016, "Andrew Stanton");
DVD lionKingDVD = new DVD("The Lion King", 2019, "Jon Favreau");

// Put "The Incredibles" into the 4th place: index 3.
dvdCollection[3] = incrediblesDVD;

// Put "Finding Dory" into the 10th place: index 9.
dvdCollection[9] = findingDoryDVD;

// Put "The Lion King" into the 3rd place: index 2.
dvdCollection[2] = lionKingDVD;

Notice that we put The Incredibles into the Array at index 3. What happens if we now run this next piece of code?

DVD starWarsDVD = new DVD("Star Wars", 1977, "George Lucas");
dvdCollection[3] = starWarsDVD;

Because we just put Star Wars into the Array at index 3, The Incredibles is no longer in the Array. It has been overwritten! If we still have the incrediblesDVD variable in scope, then the DVD still exists in the computer's memory. If not though, it's totally gone!

 

우리는 Star Wars를 인덱스 3의 Array에 넣었 기 때문에 The Incredibles는 더 이상 Array에 없습니다. 덮어 썼습니다! 범위에 여전히 amazingsDVD 변수가 있으면 DVD는 컴퓨터의 메모리에 여전히 존재합니다. 그렇지 않다면 완전히 사라졌습니다!

 

 

Reading Items from an Array

We can check what's at a particular Array index.

 

// Print out what's in indexes 7, 10, and 3.
System.out.println(dvdCollection[7]);
System.out.println(dvdCollection[10]);
System.out.println(dvdCollection[3]);

// Will print:

// The Avengers, directed by Joss Whedon, released in 2012
// null
// Star Wars, directed by George Lucas, released in 1977

 

Notice that because we haven't yet put anything at index 10, the value it contains is null. In other languages, such as C, the Array slot could contain completely random data. Java always initializes empty Array slots to null if the Array contains objects, or to default values if it contains primitive types. For example, the array int [] would contain the default value of 0 for each element, float[] would contain default values of 0.0, and bool[] would contain default values of false.

 

 

아직 인덱스 10에 아무것도 입력하지 않았기 때문에 포함 된 값은 null입니다. C와 같은 다른 언어에서는 배열 슬롯에 완전히 임의의 데이터가 포함될 수 있습니다. Java는 Array에 객체가 포함 된 경우 항상 빈 Array 슬롯을 null로 초기화하고 기본 유형을 포함하는 경우 기본값으로 초기화합니다. 예를 들어, 배열 int []에는 각 요소에 대한 기본값 0이 포함되고 float []에는 기본값 0.0이 포함되며 bool []에는 기본값 false가 포함됩니다.

 

Writing Items into an Array with a Loop


We commonly use a loop to put lots of values into an Array. To illustrate this, let's go to another example. This time, we're going to create an Array of ints and put the first 10 square numbers into it.

 

int[] squareNumbers = new int[10];

// Go through each of the Array indexes, from 0 to 9.
for (int i = 0; i < 10; i++) {
    // We need to be careful with the 0-indexing. The next square number
    // is given by (i + 1) * (i + 1).
    // Calculate it and insert it into the Array at index i.
    int square = (i + 1) * (i + 1);
    squareNumbers[i] = square;
}

Reading Items from an Array with a Loop


We can also use a loop to print out everything that's in the Array.

 

// Go through each of the Array indexes, from 0 to 9.
for (int i = 0; i < 10; i++) {
    // Access and print what's at the i'th index.
    System.out.println(squareNumbers[i]);
}

// Will print:
// 1
// 4
// 9
// 16
// 25
// 36
// 49
// 64
// 81
// 100

One last thing worth knowing now is that there's a more elegant way of printing out the values of an Array—a variant of the for loop, commonly referred to as a "for each" loop.

 

// For each VALUE in the Array.
for (int square : squareNumbers) {
    // Print the current value of square.
    System.out.println(square);
}
// Prints exactly the same as the previous example.

You'll probably agree that this code is a lot simpler to read. We can use it whenever we don't need the index values. For actually writing the squares into the Array, it wouldn't have worked because we needed to work with the actual index numbers. You don't have to use a "for each" loop when you're starting out, but we recommend you become comfortable with it before interviews. Simple, elegant code is good code!

 

이 코드가 훨씬 더 읽기 쉽다는 데 동의 할 것입니다. 인덱스 값이 필요하지 않을 때마다 사용할 수 있습니다. 실제로 사각형을 배열에 쓰는 경우 실제 인덱스 번호로 작업해야했기 때문에 작동하지 않았을 것입니다. 시작할 때 "for each"루프를 사용할 필요는 없지만 인터뷰 전에 익숙해지는 것이 좋습니다. 간단하고 우아한 코드는 좋은 코드입니다!

 

 

 


Array Capacity VS Length


If somebody asks you how long the DVD Array is, what what would your answer be?

There are two different answers you might have given.

  1. The number of DVDs the box could hold, if it was full, or
  2. The number of DVDs currently in the box.

Both answers are correct, and both have very different meanings! It's important to understand the difference between them, and use them correctly. We call the first one the capacity of the Array, and the second one the length of the Array.

 

Array Capacity


Let's say we've created a new Array like this.

DVD[] array = new DVD[6]

Is it a valid operation to insert an element at array[6]? What about at array[10]?

Nope, neither of these are valid. When we created the Array, we specified that it can hold up to 6 DVD's. This is the Array's capacity.

Remembering that indexing starts at 0, we can only insert items at array[0], array[1], array[2], array[3], array[4], and array[5]. Trying to put an element anywhere else, such as array[-3], array[6], or array[100] will cause your code to crash with an ArrayIndexOutOfBoundsException!

The Array's capacity must be decided when the Array is created. The capacity cannot be changed later. Going back to our DVD's-in-a-cardboard-box-analogy, changing the capacity of an Array would be akin to trying to make a cardboard box bigger. Trying to make a fixed-size cardboard box bigger is impractical, and it's the same as an Array on a computer!

So, what do we do if we get a 7th DVD and we'd like all our DVD's in the same Array? Well, unfortunately it's the same as it is with our cardboard box. We'll need to go get a larger one, and then move all the existing DVD's into it, along with the new one.

The capacity of an Array in Java can be checked by looking at the value of its length attribute. This is done using the code arr.length, where arr is the name of the Array. Different programming languages have different ways of checking the length of an Array.

int capacity = array.length; System.out.println("The Array has a capacity of " + capacity);

Running this code will give the following output:

The Array has a capacity of 6

Yup, it's a bit confusing that you need to access the capacity of an Array by using .length. Unfortunately, this is just something you'll need to get used to.

 

Array Length


The other definition of length is the number of DVDs, or other items, currently in the Array. This is something you'll need to keep track of yourself, and you won't get any errors if you overwrite an existing DVD, or if you leave a gap in the Array.

You might have noticed that we've been using a length variable in our previous examples, to keep track of the next empty index.

 

어레이 용량 대 길이
누군가가 DVD 어레이의 길이를 묻는다면 어떤 대답을 하시겠습니까?

당신이 준 두 가지 다른 대답이 있습니다.

상자가 가득 찬 경우 상자에 넣을 수있는 DVD 수 또는
현재 상자에 들어있는 DVD 수입니다.
두 대답 모두 정확하며 둘 다 매우 다른 의미를 가지고 있습니다! 그 차이를 이해하고 올바르게 사용하는 것이 중요합니다. 첫 번째 것을 어레이의 용량이라고하고 두 번째를 어레이의 길이라고합니다.



어레이 용량
이와 같은 새 배열을 만들었다 고 가정 해 보겠습니다.

DVD [] 어레이 = 새 DVD [6]
array [6]에 요소를 삽입하는 것이 유효한 작업입니까? array [10]은 어떻습니까?

아니요, 둘 다 유효하지 않습니다. 어레이를 만들 때 최대 6 개의 DVD를 저장할 수 있도록 지정했습니다. 이것이 어레이의 용량입니다.

인덱싱이 0에서 시작된다는 점을 기억하면 array [0], array [1], array [2], array [3], array [4] 및 array [5]에만 항목을 삽입 할 수 있습니다. array [-3], array [6] 또는 array [100]과 같은 다른 위치에 요소를 배치하려고하면 ArrayIndexOutOfBoundsException과 함께 코드가 충돌합니다!

어레이의 용량은 어레이가 생성 될 때 결정되어야합니다. 용량은 나중에 변경할 수 없습니다. DVD의 -in-a-cardboard-box-analogy로 돌아가서 어레이의 용량을 변경하는 것은 판지 상자를 더 크게 만드는 것과 비슷할 것입니다. 고정 된 크기의 판지 상자를 더 크게 만드는 것은 비현실적이며 컴퓨터의 배열과 동일합니다!

그렇다면 7 번째 DVD를 얻고 모든 DVD를 동일한 어레이에 넣으려면 어떻게해야합니까? 글쎄, 안타깝게도 우리 골판지 상자와 동일합니다. 더 큰 DVD를 구입 한 다음 기존 DVD를 새 DVD와 함께 모두 옮겨야합니다.

Java에서 Array의 용량은 length 속성의 값을보고 확인할 수 있습니다. 이는 arr 코드를 사용하여 수행됩니다. 여기서 arr은 배열의 이름입니다. 프로그래밍 언어마다 배열 길이를 확인하는 방법이 다릅니다.

이 코드를 실행하면 다음 출력이 제공됩니다.

어레이의 용량은 6입니다.
를 사용하여 어레이의 용량에 액세스해야한다는 것은 약간 혼란 스럽습니다. 길이. 불행히도 이것은 당신이 익숙해 져야 할 것입니다.



어레이 길이
길이의 다른 정의는 현재 어레이에있는 DVD 또는 기타 항목의 수입니다. 이것은 자신을 추적해야하는 사항이며 기존 DVD를 덮어 쓰거나 어레이에 공백을 남겨도 오류가 발생하지 않습니다.

다음 빈 인덱스를 추적하기 위해 이전 예제에서 길이 변수를 사용하고 있음을 알 수 있습니다.

 

// Create a new array with a capacity of 6.
int[] array = new int[6];

// Current length is 0, because it has 0 elements.
int length = 0;

// Add 3 items into it.
for (int i = 0; i < 3; i++) {
    array[i] = i * i;
    // Each time we add an element, the length goes up by one.
    length++;
}

System.out.println("The Array has a capacity of " + array.length);
System.out.println("The Array has a length of " + length);

Running this code will give the following output:The Array has a capacity of 6 The Array has a length of 3

 

 

 

 

Handling Array Parameters


Most Array questions on LeetCode have an Array passed in as a parameter, with no "length" or "capacity" parameter. What do we mean by this? Well, let's look at an example. Here is the description for the first problem you'll be asked to solve.

Given a binary array, find the maximum number of consecutive 1s in this array.

And here is the code template you're given.

The only parameter is nums; an Array. You couldn't possibly solve this question without knowing how long nums is. Well, luckily it's straightforward. When an Array is given as a parameter, without any additional information, you can safely assume that length == capacity. That is, the Array is the exact right size to hold all of it's data. We can, therefore, use .length.

Be careful though, Array's are 0-indexed. The capacity/ length is a number of items, not a highest index. The highest index is .length - 1. Therefore, to iterate over all items in the Array, we can do the following.

 

배열 매개 변수 처리
LeetCode에 대한 대부분의 Array 질문에는 "length"또는 "capacity"매개 변수없이 매개 변수로 전달 된 Array가 있습니다. 이것은 무엇을 의미합니까? 음, 예를 살펴 보겠습니다. 다음은 해결해야 할 첫 번째 문제에 대한 설명입니다.

이진 배열이 주어지면이 배열에서 연속되는 1의 최대 수를 찾습니다.

여기에 제공된 코드 템플릿이 있습니다.


유일한 매개 변수는 nums입니다. 배열. 숫자가 얼마나 긴지 모른 채이 질문을 풀 수 없습니다. 다행히도 간단합니다. 추가 정보없이 배열이 매개 변수로 제공되면 길이 == 용량이라고 안전하게 가정 할 수 있습니다. 즉, Array는 모든 데이터를 보관하기에 정확한 크기입니다. 따라서 .length를 사용할 수 있습니다.

하지만 조심하세요. Array의 인덱스는 0입니다. 용량 / 길이는 가장 높은 지수가 아닌 항목 수입니다. 가장 높은 인덱스는 .length-1입니다. 따라서 Array의 모든 항목을 반복하려면 다음을 수행 할 수 있습니다.

 

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        // Hint: Initialise and declare a variable here to 
        // keep track of how many 1's you've seen in a row.
        for (int i = 0; i < nums.length; i++) {
            // Do something with element nums[i].
        }
    }
}

And that is the basics of Arrays that you'll need to get started! In the next chapter, we'll look at some of the fundamental techniques we use to work with Arrays.

Before that though, we have a few introductory Array problems for you to play around with, starting with the one we briefly looked at above. Enjoy!

 

이것이 바로 시작하는 데 필요한 어레이의 기본입니다! 다음 장에서는 배열 작업에 사용하는 몇 가지 기본 기술을 살펴 보겠습니다.

하지만 그 전에는 위에서 간략히 살펴본 문제부터 시작하여 가지고 놀 수있는 몇 가지 소개 배열 문제가 있습니다. 즐겨!

반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band