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;i<A.length;i++){
        	if(A[i] == elem)
        		count++;
        	else if(count>0)
        		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<A.length;i++){
        	if(A[i]!=elem){
        		A[count++]=A[i];
        	}else{
        		continue;
        	}
        }
        return count;
    }


c++

int removeElement(int A[], int n, int elem) {
        int cur =0;
    for(int i=0;i<n;i++){
        if(A[i]==elem)
            continue;
        A[cur] = A[i];
        cur++;
    }
    return cur;
    }

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;i++){
        	while(A[i]!=i+1){
        		if(A[i]<=0 ||A[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<A.length;i++){
        	if(A[i]!=i+1)
        		return i+1;
        }
        return A.length+1;
    }

c++

int firstMissingPositive(int A[], int n) {
        int i=0;
    while(i<n){
        if(A[i]!=i+1 && A[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<n;i++){
        if(A[i]!=i+1)
            return i+1;
    }
    return n+1;
    }

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<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>();
    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<int> spiralOrder(vector<vector<int> > &matrix) {
    vector<int> 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<vector<int> > generateMatrix(int n) {
        vector<vector<int>> matrix(n);
     if(n == 0) return matrix;
     for(int i=0; i<n; i++){
        matrix[i].resize(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 j = y1; j<=y2; ++j)
            matrix[x1][j] = val++;
        for(int i = x1+1; i<=x2; ++i)
            matrix[i][y2] = val++;
        if(x2 !=x1)
            for(int j = y2-1; j>=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<vector<int> > generateMatrix(int n) {
        vector<vector<int>> matrix(n);
     if(n == 0) return matrix;
     for(int i=0; i<n; i++){
        matrix[i].resize(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 j = y1; j<=y2; ++j)
            matrix[x1][j] = val++;
        for(int i = x1+1; i<=x2; ++i)
            matrix[i][y2] = val++;
        if(x2 !=x1)
            for(int j = y2-1; j>=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<length/2; i++){
        	for(int j=0; j<length; j++){
        		int temp = matrix[i][j];
        		matrix[i][j] = matrix[length-i-1][j];
        		matrix[length-i-1][j] = temp;
        	}
        }
        for(int i=0; i<length; i++){
        	for(int j=0; j<i+1;j++){
        		int temp = matrix[i][j];
        		matrix[i][j] = matrix[j][i];
        		matrix[j][i] = temp;
        	}
        }
    }

c++

void rotate(vector<vector<int> > &matrix) {
        int length = matrix.size();
    for(int i=0;i<length/2;i++){
        for(int j=0;j<length;j++){
            swap(matrix[i][j],matrix[length-1-i][j]);
        }
    }
    for(int i=0;i<length;i++){
        for(int j=0;j<i+1;j++){
            swap(matrix[i][j],matrix[j][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<vector<int> > generateMatrix(int n) {
        vector<vector<int>> matrix(n);
     if(n == 0) return matrix;
     for(int i=0; i<n; i++){
        matrix[i].resize(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 j = y1; j<=y2; ++j)
            matrix[x1][j] = val++;
        for(int i = x1+1; i<=x2; ++i)
            matrix[i][y2] = val++;
        if(x2 !=x1)
            for(int j = y2-1; j>=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;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值