Leetcode之数组问题

1. Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Analysis:

two pointers scan, one variable record the frequency of the value, detailed see in code

Java

public int removeElement(int[] A, int elem) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int count = 0;
        for(int i=0;i0)
        		A[i-count] = A[i];
        }
		return A.length - count;
    }

Another one:

public int removeElement(int[] A, int elem) {
        int count = 0;
        for(int i=0;i


c++

int removeElement(int A[], int n, int elem) {
        int cur =0;
    for(int i=0;i

2. Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.

Analysis:

The classic problem. (can be found in the book "Cracking the Code Interview").
Part of the merge sort, merge the arrays from the back by comparing the elements.

Java

public void merge(int A[], int m, int B[], int n) {
        int count = m+n-1;
        m--;n--;
        while(m>=0 && n>=0){
        	A[count--] = A[m]>B[n]? A[m--]:B[n--];
        }
        while(n>=0)
        	A[count--] = B[n--];
    }

c++

void merge(int A[], int m, int B[], int n) {
        int count = m+n-1;
        m--;n--;
        while(m>=0 && n>=0){
        	A[count--] = A[m]>B[n]? A[m--]:B[n--];
        }
        while(n>=0)
        	A[count--] = B[n--];
    }


3. First Missing Positive

Given an unsorted integer array, find the first missing positive integer.

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

Analysis:

其实就是桶排序,只不过不许用额外空间。所以,每次当A[i]!= i的时候,将A[i]与A[A[i]]交换,直到无法交换位置。终止条件是 A[i]== A[A[i]]。
然后i -> 0 到n走一遍就好了。

Java

public int firstMissingPositive(int[] A) {
        for(int i=0;i=A.length|| A[i]==A[A[i]-1]) break;
        		int temp = A[i];
        		A[i] = A[A[i]-1];
        		A[temp-1] = temp;
        	}
        	
        }
        for(int i=0;i

c++

int firstMissingPositive(int A[], int n) {
        int i=0;
    while(i=1 &&A[i]<=n && A[A[i]-1] !=A[i])
            swap(A[i],A[A[i]-1]);
        else
            i++;
    }
    for(int i=0; i

4. Spiral Matrix I 

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Analysis:

We could solve this problem straight forward. Output is element in order: up->right->down->left layer from layer. 

every time we ouput its most outside rectangle, use (x1,y1) (x2,y2) represent

it can be achieved in while loop, the codition is x1<=x2 && y1<=y2

Java

public List spiralOrder(int[][] matrix) {
        ArrayList result = new ArrayList();
    int x1 = 0;
    int y1 = 0;
    int x2 = matrix.length-1;
    if(x2<0) return result;
    int y2 = matrix[0].length-1;
    while(x1<=x2 && y1<=y2){
    	for(int i=y1;i<=y2;i++){//right
    		result.add(matrix[x1][i]);
    	}
    	for(int j=x1+1;j<=x2;j++){//down
    		result.add(matrix[j][y2]);
    	}
    	if(x1!=x2){
    		for(int i=y2-1;i>=y1;i--){//left
    			result.add(matrix[x2][i]);
    		}
    	}
    	if(y1!=y2){//up
    		for(int j=x2-1;j>x1;j--){
    			result.add(matrix[j][y1]);
    		}
    	}
    	x1++; y1++; x2--;y2--;
    }
    return result;
    }
c++
vector spiralOrder(vector > &matrix) {
    vector result;
     if(matrix.size() == 0) return result;
     int x1 = 0;
     int y1 = 0;
     int x2 = matrix.size() - 1;
     int y2 = matrix[0].size() - 1;
     while(x1<=x2 && y1<=y2){
        //up row
        for(int j = y1; j<=y2; ++j){
            result.push_back(matrix[x1][j]);
        }
        // right column
        for(int i = x1+1; i<=x2; ++i){
            result.push_back(matrix[i][y2]);
        }
        
        if(x2 !=x1){
        // bottom row
        for(int j = y2-1; j>=y1; --j){
            result.push_back(matrix[x2][j]);
        }}
       
        if(y2 != y1){
        // left column
        for(int i = x2-1; i>x1; --i){
            result.push_back(matrix[i][y1]);
        }}
        x1++, y1++, x2--, y2--;
     }
     return result;
    }


5. Spiral Matrix II


Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
Analysis:

Similiar with the former one Spiral Matrix

Java

public int[][] generateMatrix(int n) {
        int [][] result = new int[n][n];
        int x1=0;
        int y1=0;
        int x2=n-1;
        int y2 = n-1;
        int val = 1;
        while(x1<=x2 && y1<=y2){
        	for(int i=y1;i<=y2;i++)
        		result[x1][i] = val++;
        	for(int j = x1+1;j<=x2;j++)
        		result[j][y2] = val++;
        	if(x1!=x2)
        		for(int i=y2-1;i>=y1;i--)
        			result[x2][i] = val++;
        	if(y1!=y2)
        		for(int j=x2-1;j>y1;j--)
        			result[j][y1]=val++;
        	x1++;y1++;x2--;y2--;
        }
        return result;
    }

c++

vector > generateMatrix(int n) {
        vector> matrix(n);
     if(n == 0) return matrix;
     for(int i=0; i=y1; --j)
                matrix[x2][j] = val++;
        if(y2 != y1)
            for(int i = x2-1; i>x1; --i)
                matrix[i][y1] = val++;
        x1++, y1++, x2--, y2--;
     }
     return matrix;
    }


6. Rotate Image

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
Analysis:

Similiar with the former one Spiral Matrix

Java

public int[][] generateMatrix(int n) {
        int [][] result = new int[n][n];
        int x1=0;
        int y1=0;
        int x2=n-1;
        int y2 = n-1;
        int val = 1;
        while(x1<=x2 && y1<=y2){
        	for(int i=y1;i<=y2;i++)
        		result[x1][i] = val++;
        	for(int j = x1+1;j<=x2;j++)
        		result[j][y2] = val++;
        	if(x1!=x2)
        		for(int i=y2-1;i>=y1;i--)
        			result[x2][i] = val++;
        	if(y1!=y2)
        		for(int j=x2-1;j>y1;j--)
        			result[j][y1]=val++;
        	x1++;y1++;x2--;y2--;
        }
        return result;
    }

c++

vector > generateMatrix(int n) {
        vector> matrix(n);
     if(n == 0) return matrix;
     for(int i=0; i=y1; --j)
                matrix[x2][j] = val++;
        if(y2 != y1)
            for(int i = x2-1; i>x1; --i)
                matrix[i][y1] = val++;
        x1++, y1++, x2--, y2--;
     }
     return matrix;
    }





You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

Analysis:

This is a classic problem in Craking Coding interview, 1.6

The key idea is to rotate the matrix according to layers. For the nth layer(the out layer), rotate 90 degree is to move all the elements n times in a circle. In each layer, the rotation can be performed by first swap 4 corners, then swap 4 elements next to corner until the end of each line.

While there is another soulution could calculate index easily.

1. lap over along with x-axis2

2. lap over along with diagonal line

Java

public void rotate(int[][] matrix) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int length = matrix.length;
        // swap the diagnoal
        for(int i=0; i

c++

void rotate(vector > &matrix) {
        int length = matrix.size();
    for(int i=0;i









Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
Analysis:

Similiar with the former one Spiral Matrix

Java

public int[][] generateMatrix(int n) {
        int [][] result = new int[n][n];
        int x1=0;
        int y1=0;
        int x2=n-1;
        int y2 = n-1;
        int val = 1;
        while(x1<=x2 && y1<=y2){
        	for(int i=y1;i<=y2;i++)
        		result[x1][i] = val++;
        	for(int j = x1+1;j<=x2;j++)
        		result[j][y2] = val++;
        	if(x1!=x2)
        		for(int i=y2-1;i>=y1;i--)
        			result[x2][i] = val++;
        	if(y1!=y2)
        		for(int j=x2-1;j>y1;j--)
        			result[j][y1]=val++;
        	x1++;y1++;x2--;y2--;
        }
        return result;
    }

c++

vector > generateMatrix(int n) {
        vector> matrix(n);
     if(n == 0) return matrix;
     for(int i=0; i=y1; --j)
                matrix[x2][j] = val++;
        if(y2 != y1)
            for(int i = x2-1; i>x1; --i)
                matrix[i][y1] = val++;
        x1++, y1++, x2--, y2--;
     }
     return matrix;
    }




你可能感兴趣的:(Leetcode)