'Algorithm > 필수 문법' 카테고리의 다른 글

파이썬3 필수 문법  (0) 2019.07.19
C++ sort  (0) 2019.04.23
구글 코딩 스타일  (0) 2019.04.09
Python, Java, C++ 알고리즘 문제 풀 때 기본 문법 차이  (0) 2019.04.05
Posted by 공놀이나하여보세
,

'Algorithm > 필수 문법' 카테고리의 다른 글

파이썬3 필수 문법  (0) 2019.07.19
C++ sort  (0) 2019.04.23
코드 예쁘게 붙여 넣기  (0) 2019.04.09
Python, Java, C++ 알고리즘 문제 풀 때 기본 문법 차이  (0) 2019.04.05
Posted by 공놀이나하여보세
,

오늘은 LeetCode를 풀 때 필수 문법에 대해 정리해 보겠습니다.

다양한 언어를 접했던 관계로 LeetCode를 풀 때 상황에 따라 언어를 바꾸다 보니 저도 헷깔려서 정리해 봅니다.

 

(1) Java

a. System.out.println("a + b = " + c);

b. class{

}

c. int 선언 시 new를 해야함

int test[][] = new int[1000][1000];

d. 배열의 길이

test.length

test[0].length

 

(2) Python2.x

a. print "a + b = %d", (c);

b. 

c. 

d. 리스트의 길이

len(test)

len(test[0])

e. for문

for i in range(len(nums)):

 

(3) C++

a. cout << "a + b = " << c << endl;

b. class 끝에 세미콜론을 붙인다.

class{

}; 

c. 벡터 선언

// assumes using std::vector for brevity

vector<vector<int>> matrix(RR, vector<int>(CC));

또는

vector<vector<int> > matrix;

for(int i = 0; i<RR; i++) {

    vector<int> myvector;

    for(int j = 0; j<CC; j++)

   {

        int tempVal = 0;

        cout<<"Enter the number for Matrix 1";

        cin>>tempVal;

        myvector.push_back(tempVal);

    }

    matrix.push_back(myvector);

}

 

d. 벡터의 길이

test.size()

test[0].size()

생각날 때마다 계속 업데이트 하겠습니다.

'Algorithm > 필수 문법' 카테고리의 다른 글

파이썬3 필수 문법  (0) 2019.07.19
C++ sort  (0) 2019.04.23
코드 예쁘게 붙여 넣기  (0) 2019.04.09
구글 코딩 스타일  (0) 2019.04.09
Posted by 공놀이나하여보세
,

회사 역량 시험은 C, C++, Java 만 가능한데, Java는 재귀 함수 사용 시 메모리 문제가 발생할 수 있다고 해서,

C++로 하기로 결정!!

 

Number of Islands 를 java로 다시 풀어보았다.

이전과 같이, DFS : Depth First Search 깊이 우선 탐색 알고리즘이며 재귀함수 호출 방식이다.

C++ 문법이 헷깔려서 다른 사람 코드를 언뜻 봤는데, 알고리즘이 좋아서 나도 참조해 보았다.

class Solution {
public:
    int r_length = 0;
    int c_length = 0;
    
    void findOne(vector<vector>& grid, int r, int c){
        if(r < 0 || r >= r_length || c < 0 || c >= c_length)
            return;
        
        if(grid[r][c] == '0')
            return;
        
        grid[r][c] = '0';
        
        findOne(grid, r, c-1);
        findOne(grid, r, c+1);
        findOne(grid, r-1, c);
        findOne(grid, r+1, c);
        
        return;
    }
    int numIslands(vector<vector>& grid) {
        r_length = grid.size();
        
        if(grid.size() == 0)
            return 0;
        c_length = grid[0].size();
        
        int cnt = 0;
        for(int i = 0; i < r_length; i++){
            for(int j = 0; j < c_length; j++){
                if(grid[i][j] == '1'){
                    cnt++;
                    findOne(grid, i, j);
                }
            }
        }
        
        return cnt;
    }
    
};

출처 : https://leetcode.com/problems/number-of-islands/discuss/266379/(98.93-100)-DFS-C%2B%2B

Posted by 공놀이나하여보세
,

 

https://leetcode.com/problems/construct-the-rectangle/submissions/

그냥 질문 그대로 구현했다.

좀 느릴 것 같다.

class Solution {
    public int[] constructRectangle(int area) {
        int value[] = new int[2];
        if(area == 0){
            value[0] = 0;
            value[1] = 0;
            return value;
        }
        else if(area == 1){
            value[0] = 1;
            value[1] = 1;
            return value;
        }

        int difference = area;
        int start = 1;
        int end = area;
        int a, b;
        for(int i = start; i <= end; i++){
            if(area % i == 0){
                a = i;
                b = area / i;
            
                if((a >= b)&&((a-b)<difference)){
                    difference = value[0] - value[1];
                    value[0] = a;
                    value[1] = b;
           
                }
            }
        }
        return value;
    }
}

Posted by 공놀이나하여보세
,

4. 485 : Max Consecutive Ones

https://leetcode.com/problems/max-consecutive-ones/submissions/

 

Loading...

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

예외 처리에 주의해야겠다.

 

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        cnt = 0
        max = 0
        
        for i in range(len(nums)):
            if nums[i] == 1:
                cnt += 1
            else:
                if max < cnt:
                    max = cnt
                cnt = 0
        
        if max < cnt:
            max = cnt
                
        return max        
        """
        :type nums: List[int]
        :rtype: int
        """

 

Posted by 공놀이나하여보세
,

3. 290 : word pattern

s = str.split(' ')

class Solution(object):
    def wordPattern(self, pattern, str):
        s = str.split(' ')
        
        if len(s) != len(pattern):
            return False
       
        for i in range(len(s)):
            for j in range(i + 1, len(s)):
                if pattern[i] == pattern[j]:
                    if s[i] != s[j]:
                        return False
                else:
                    if s[i] == s[j]:
                        return False
            
        return True
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """

 

Posted by 공놀이나하여보세
,

파이썬은 리스트가 잘 되어 있어서 구현이 쉬웠음

class Solution(object):
    def moveZeroes(self, nums):
        if len(nums) == 0:
            return
        
        for i in range(len(nums)):
            if(nums[i] == 0):
                nums.remove(0)
                nums.append(0)
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """

 

Posted by 공놀이나하여보세
,

1. 232 : implement Queue using Stacks

class MyQueue(object):

    def __init__(self):
        self.data = []
        self.size = 0
        
        """
        Initialize your data structure here.
        """
        

    def push(self, x):
        self.data.append(x)
        self.size += 1
        #print self.data
        
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: None
        """
        
    def pop(self):
        if(self.size > 0):
            self.size -= 1
            pop_data = self.data[0]
            self.data.remove(pop_data)
            return pop_data
            
        return 0
        
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        

    def peek(self):
        if(self.size > 0):
            #print self.data[0]
            return self.data[0]
        else:
            return 0
        
        """
        Get the front element.
        :rtype: int
        """
        

    def empty(self):
        if self.size == 0:
            return 1
        else:
            return 0
        
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

 

Posted by 공놀이나하여보세
,

그냥 하나 풀 때마다 하나씩 여기에 정리해야겠다.

True False 첫글자는 꼭 대문자로 해야한다.

5. 492 : Construct the Rectangle

BST

6. 501. Find Mode in Binary Search Tree
Minimum Absolute Difference in BST
543. Diameter of Binary Tree
563. Binary Tree Tilt

linked list
203. Remove Linked List Elements
206. Reverse Linked List

conversion
504. Base 7

string
557. Reverse Words in a String III
189. Rotate Array
599. Minimum Index Sum of Two Lists

matrix
566. Reshape the Matrix

783. Minimum Distance Between BST Nodes

 

Hash 

705. Design HashSet

 

그 다음에 graph로 넘어가기


완료 소스

1. 232 : implement Queue using Stacks

class MyQueue(object):

    def __init__(self):
        self.data = []
        self.size = 0
        
        """
        Initialize your data structure here.
        """
        

    def push(self, x):
        self.data.append(x)
        self.size += 1
        #print self.data
        
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: None
        """
        
    def pop(self):
        if(self.size > 0):
            self.size -= 1
            pop_data = self.data[0]
            self.data.remove(pop_data)
            return pop_data
            
        return 0
        
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        

    def peek(self):
        if(self.size > 0):
            #print self.data[0]
            return self.data[0]
        else:
            return 0
        
        """
        Get the front element.
        :rtype: int
        """
        

    def empty(self):
        if self.size == 0:
            return 1
        else:
            return 0
        
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

2. 283 : Move Zeroes

리스트에 대해 많이 배울 수 있었다.

class Solution(object):
    def moveZeroes(self, nums):
        if len(nums) == 0:
            return
        
        for i in range(len(nums)):
            if(nums[i] == 0):
                nums.remove(0)
                nums.append(0)
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        

3. 290 : word pattern

 

class Solution(object):
    def wordPattern(self, pattern, str):
        s = str.split(' ')
        
        if len(s) != len(pattern):
            return False
       
        for i in range(len(s)):
            for j in range(i + 1, len(s)):
                if pattern[i] == pattern[j]:
                    if s[i] != s[j]:
                        return False
                else:
                    if s[i] == s[j]:
                        return False
            
        return True
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """

 

4. 485 : Max Consecutive Ones

https://leetcode.com/problems/max-consecutive-ones/submissions/

불러오는 중입니다...

예외 처리에 주의해야겠다.

 

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        cnt = 0
        max = 0
        
        for i in range(len(nums)):
            if nums[i] == 1:
                cnt += 1
            else:
                if max < cnt:
                    max = cnt
                cnt = 0
        
        if max < cnt:
            max = cnt
                
        return max        
        """
        :type nums: List[int]
        :rtype: int
        """
        

Posted by 공놀이나하여보세
,