↓ Skip to main content
  1. Posts/

leetcode 73. Set Matrix Zeroes (矩阵置0,乱搞)

·926 words·2 mins
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

**Follow up:**Did you use extra space? A straight forward solution using O(m__n) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution?

直接放常数空间的做法。

这道题面hypereal的时候遇到过,基本思路就是用已经确定是0的位置来存储其他行和列的信息。

三点注意:

  *   (x,y)不要放任何信息,不然行和列的信息,后面处理的那个可能被覆盖掉。
  *   (x,y)位置要进行标记,否则默认的0值可能会造成歧义
  * 赋值成0的时候要分成两部分,处理的时候避免因为处理前面赋值成了0,把后面标记的行和列的标号覆盖掉。
代码实现
 1/* ***********************************************
 2Author :111qqz
 3Created Time :2017年04月10日 星期一 08时06分27秒
 4File Name :73.cpp
 5************************************************ */
 6class Solution {
 7public:
 8    void setZeroes(vector<vector<int>>& a) {
 9	int n = a.size();
10	int m = a[0].size();
11	bool ok = false;
12	int x,y;
13	x = y = -1;
14	for ( int i = 0 ; i < n ; i++)
15	{
16	    if (ok) break;
17	    for ( int j =  0 ; j < m; j++)
18	    {
19		if (a[i][j]==0)
20		{
21		    x = i;
22		    y = j;
23		    ok = true;
24		    break;
25		}
26	    }
27	}
28	if (x==-1) return ; //没有0存在
29
30
31	int cntx=0,cnty=0;
32	for ( int i = 0 ; i < n ; i++) // note to avoid the (x,y) to record any info,or it may be coverd by the latter info
33	{
34	    if (i!=x)
35	    for ( int j = 0 ;j  < m ; j++)
36	    {
37		if (a[i][j]==0)
38		{
39		    if (cntx==x)
40		    {
41			a[cntx][y] = -1;
42			cntx++;
43		    }
44		    a[cntx++][y] = i;
45		    break;
46		}
47	    }
48	}
49	for ( int j = 0 ; j < m ; j++)
50	{
51	    if (j!=y)
52	    for ( int  i = 0 ; i < n ; i++)
53	    {
54		if (a[i][j]==0)
55		{
56		    if (cnty==y)
57		    {
58			a[x][cnty] = -1; // set a mark the (x,y),or the original value 0 will mislead the program.
59			cnty++;
60		    }
61		    a[x][cnty++] = j ;
62		    break;
63		}
64	    }
65	}
66	for ( int i =  0 ; i < cntx ; i++)
67	{
68	    int XX = a[i][y];
69
70	    if (XX==x||XX==-1) continue;
71	    for ( int j = 0 ; j < m ; j++)
72		if (j!=y)   // fill the 0 in two steps,ensuring not to cover the info
73		a[XX][j] = 0 ;
74	}
75	for ( int j = 0 ; j < cnty ; j++)
76	{
77	    int YY = a[x][j];
78	    if (y==YY||YY==-1) continue;
79	//    cout<<"YY:"<<YY<<endl;
80	    for (int i = 0 ; i < n ; i++)
81		if (i!=x)
82		a[i][YY] = 0;
83	}
84	for ( int i = 0 ; i < n ; i++)
85	    for ( int j = 0 ; j < m ; j++)
86		if (i==x||j==y) a[i][j] = 0 ;
87    }
88};

下面有一个更精简的思路:

直接用每一行和每一列的第一个位置记录相应行和相应列的状态((0,0)点会有重合,再加一个变量记录就好)

得到信息后记得从右下角往左上更新,避免信息覆盖。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2017年04月10日 星期一 08时06分27秒
 4File Name :73.cpp
 5************************************************ */
 6class Solution {
 7public:
 8 void setZeroes(vector<vector<int> > &matrix) {
 9    int col0 = 1, n = matrix.size(), m = matrix[0].size();
10
11    for (int i = 0; i < n; i++) {
12        if (matrix[i][0] == 0) col0 = 0;
13        for (int j = 1; j < m; j++)
14            if (matrix[i][j] == 0)
15                matrix[i][0] = matrix[0][j] = 0;
16    }
17
18    for (int i = n-1; i >=0 ;i--) {
19        for (int j = m-1; j >=1; j--)
20            if (matrix[i][0] == 0 || matrix[0][j] == 0)
21                matrix[i][j] = 0;
22        if (col0 == 0) matrix[i][0] = 0;
23    }
24 }
25};

Related

leetcode 238. Product of Array Except Self (乱搞)

·411 words·1 min
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Follow up: Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 先来个O(n)空间的无脑解法。。。一个前缀积一个后缀积就好了。。。

leetcode 79. Word Search (dfs)

·374 words·1 min
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. 思路:dfs即可。记得要回溯一下… 代码实现 1/* *********************************************** 2Author :111qqz 3Created Time :2017年04月07日 星期五 14时32分54秒 4File Name :79.cpp 5************************************************ */ 6class Solution { 7 8public: 9 10 int n,m; 11 const int dx4[4]={1,-1,0,0}; 12 const int dy4[4]={0,0,-1,1}; 13 bool vis[1005][1005]; 14 int len; 15 16 bool yes( int x,int y) 17 { 18 if (x>=0&&x<=n-1&&y>=0&&y<=m-1) return true; 19 return false; 20 } 21 22 bool dfs( int x,int y,int cur,vector<vector<char> > & maze,string & st) 23 { 24// printf("x:%d y:%d cur : %d\n",x,y,cur); 25 if (cur>=len) return true; 26 for ( int i = 0 ; i < 4 ; i++) 27 { 28 int nx = x + dx4[i]; 29 int ny = y + dy4[i]; 30 if (!yes(nx,ny)) continue; 31 if (vis[nx][ny]) continue; 32 if (maze[nx][ny]!=st[cur]) continue; 33 vis[nx][ny] = true; 34 bool res = dfs(nx,ny,cur+1,maze,st); 35 if (res) return true; 36 vis[nx][ny] = false ;//好像还要回溯一下啊? 37 } 38 return false; 39 } 40 41 bool exist(vector<vector<char>>& board, string word) { 42 n = board.size(); 43 if (n==0) return false; 44 m = board[0].size(); 45 if (m==0) return false; 46 len = word.length(); 47 cout<<"len:"<<len<<endl; 48 char beg = word[0]; 49 for ( int i = 0 ; i < n ; i++) 50 for ( int j = 0 ; j < m ; j++) 51 if (board[i][j]==beg) 52 { 53 memset(vis,false,sizeof(vis)); 54 //起点忘记打标记了。。。智力-2.。。 55 vis[i][j] = true; 56 bool ok = dfs(i,j,1,board,word); 57 cout<<"ok:"<<ok<<endl; 58 if (ok) return true; 59 } 60 return false; 61 62 63 } 64 65};

leetcode 80 Remove Duplicates from Sorted Array II (有序数组去除重复元素)

·324 words·1 min
Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length. Subscribe to see which companies asked this question. 题意:一个有序数组,每个元素最多出现两次,如果大于两次,把多的去掉,返回去掉后的数组长度len,以及要求数组前len是去掉那些元素之后的元素。//语死早。。看原题好了。。

leetcode 81. Search in Rotated Sorted Array II (有重复元素的旋转数组找给定值)

·333 words·1 min
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Write a function to determine if a given target is in the array. The array may contain duplicates. 好像阿里一面的时候问过。。。 思路:肯定是二分。。。不过由于有重复元素。。。所以很恶心。。。

leetcode 289. Game of Life (模拟)

·1065 words·3 mins
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.” Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): 1. Any live cell with fewer than two live neighbors dies, as if caused by under-population. 2. Any live cell with two or three live neighbors lives on to the next generation. 3. Any live cell with more than three live neighbors dies, as if by over-population.. 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Write a function to compute the next state (after one update) of the board given its current state.