Leetcode--easy系列3

#26 Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn‘t matter what you leave beyond the new length.

------这个题提交了好几次才AC,主要是函数不仅要返回不重复数的个数count,还要求将不重复的数放置在原始数组的前count个位置,阅读理解很重要啊。

int removeDuplicates(int* nums, int numsSize) {
	int count=1;//14ms
	int i;
	if(numsSize==0)
		return 0;
	if(numsSize==1)
		return 1;
	for(i=1;i<=numsSize-1;i++)
	{
		if(nums[i]!=nums[i-1])
		{
			nums[count] = nums[i];//不仅要求出不重复个数,还要将不重复元素放在前面
			count++;
		}
	}
	return count;
}

#27 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.

从数组中去除指定元素,返回剩余元素个数count。-------同时,原来数组中前count个元素即为原来数组的剩余元素,否则不会AC。

写了2种方法,法一时间复杂度和空间复杂度都比较高,但便于理解;法二使用了双指针,i和count分别指向原来的元素和非指定删除值的元素

//0ms
int removeElement(int* nums, int numsSize, int val) {
    <span style="white-space:pre">	</span>int i,j = 0,count = 0;
	int *a;
	a = (int *)malloc(sizeof(int)*numsSize);
	for(i=0; i < numsSize; i++)
	{
		if(nums[i] == val)
			count++;
		else
			a[j++]=nums[i];

	}
	for(i=0; i < j; i++)
		nums[i] = a[i];
	return numsSize-count;
}
//0ms
int removeElement(int* nums, int numsSize, int val) {
    <span style="white-space:pre">	</span>int i = 0,count = 0;
<span style="white-space:pre">	</span>while(i < numsSize)
	{
		if(nums[i] == val)
			i++;
		else
			nums[count++] = nums[i++];
	}
	return count;
}

#28 Implement strStr()

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

经典的串的模式匹配问题,主要有BF和KMP算法,具体解析可见本博客相关博客《串模式匹配之BF和KMP算法》

//BF
int strStr(char* haystack, char* needle) {
    int i=0,j=0,k;
	int len1 = strlen(haystack);
	int len2 = strlen(needle);
	if(len2==0)
	    return 0;
	if(len1==0&&len2!=0)
	    return -1;

	while( i<len1 && j<len2)
	{
		if(haystack[i]==needle[j])
		{
			i++;
			j++;
		}
		else
		{
			i=i-j+1;
			j=0;
		}
	}
	if(j>=len2)
		k=i-len2;
	else
		k=-1;
	return k;
}

#36 Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.‘.

A partially filled sudoku which is valid.

判断给定数独是否是一个有效数独:只考虑没有重复数字,最直观的解法是判断每一列,每一行,每一个3*3的方块内不包含重复的数字

直接贴代码

bool isValidSudoku(char** board, int boardRowSize, int boardColSize) {
        int hash[10];
	int i,j,k,m,n;
	char small[3][3];
	memset(hash,0,sizeof(hash));
	if(boardRowSize%3 != 0 || boardColSize%3 != 0)
		return false;
	for(i=0; i < boardRowSize; i++)
		for(j=0;j<boardColSize;j++)
		{
			if(board[i][j] == '.'||(board[i][j] <= '9' && board[i][j] >= '1'))
				continue;
			else
				return false;
		}
	for(i = 0; i < boardRowSize; i++)
	{
	    memset(hash,0,sizeof(hash));
		for(j = 0; j < boardColSize; j++)
			if(board[i][j] != '.')
				hash[board[i][j] - '0']++;

		for(k = 1;k < 10;k++)
			if(hash[k] > 1)
				return false;
	}
	for(j = 0; j < boardColSize; j++)
	{
	    memset(hash,0,sizeof(hash));
		for(i = 0; i < boardRowSize; i++)
			if(board[i][j] != '.')
				hash[board[i][j] - '0']++;

		for(k = 1; k < 10; k++)
			if(hash[k] > 1)
				return false;
	}
	memset(hash,0,sizeof(hash));

	for(i = 0; i < boardRowSize; i = i+3)
		for(j = 0; j < boardColSize; j = j+3)
		{

			small[0][0] = board[i][j];
			small[0][1] = board[i][j+1];
			small[0][2] = board[i][j+2];
			small[1][0] = board[i+1][j];
			small[1][1] = board[i+1][j+1];
			small[1][2] = board[i+1][j+2];
			small[2][0] = board[i+2][j];
			small[2][1] = board[i+2][j+1];
			small[2][2] = board[i+2][j+2];
			for(m=0; m < 3; m++)
				for(n = 0; n < 3; n++)
				{
					if(small[m][n] != '.')
						hash[small[m][n] - '0']++;
				}

		for(k=1; k < 10; k++)
			if(hash[k] > 1)
				return false;
		memset(hash,0,sizeof(hash));
		}
	return true;
}

简化后如下:

bool isParticallyValid(char** board,int x1,int y1,int x2,int y2)
{
	int hash[10],i,j;
	memset(hash,0,sizeof(hash));
	for(i = x1; i <= x2; i++)
	{
		for(j = y1; j <= y2; j++)
		{
			if(board[i][j] != '.')
			{
			    hash[board[i][j]-'0']++;
			    if(hash[board[i][j]-'0'] > 1)
			        return false;
			}
		}
	}
	return true;
}
bool isValidSudoku(char** board, int boardRowSize, int boardColSize)
{
	int i,j;
	//判定每一行每一列是否包含重复元素
	for(i = 0; i < 9; i++)
	{
		if(!isParticallyValid(board,i,0,i,8))
			return false;
		if(!isParticallyValid(board,0,i,8,i))
			return false;
	}
	//判定3*3的方块内是否包含重复元素
	for(i = 0; i < 3; i++)
	{
		for(j = 0; j < 3; j++)
		{
			if(!isParticallyValid(board,i*3,j*3,i*3+2,j*3+2))
				return false;
		}
	}
	return true;
}
时间: 2024-09-08 18:43:18

Leetcode--easy系列3的相关文章

Leetcode permutation 系列

关于permutation的讲解,请参见http://blog.csdn.net/xuqingict/article/details/24840183 下列题目的讲解均是基于上面的文章: 题1: Next Permutation Total Accepted: 8066 Total Submissions: 32493My Submissions Implement next permutation, which rearranges numbers into the lexicographic

【Leetcode长征系列】Letter Combinations of a Phone Number

原题: Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae"

【Leetcode长征系列】Merge k Sorted Lists

原题: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:两条两条地合并.时间复杂度为O(n),n为所有链表节点和. 代码: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) :

[LeetCode蠕动系列]Sort List

这题前一阵子就看到了,一直没时间做,昨晚睡前想了想,要求n*log(n)以内的时间复杂度,第一时间想到的就是归并.快排和希尔排序(注:希尔排序时间为O(n^1.3),在数据量大于2的情况下小于n*log(n)),个人以为,链表的特性更适合归并,所以采用归并排序,实现的merge代码如下: public static ListNode merge(ListNode rhead, ListNode lhead) { ListNode head = null; if (rhead.val <= lhe

HDU 2045不easy系列之三LELE的RPG难题(趋向于DP的递推)

不easy系列之(3)-- LELE的RPG难题 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 30222 Accepted Submission(s): 12144 Problem Description 人称"AC女之杀手"的超级偶像LELE近期忽然玩起了深沉,这可急坏了众多"Cole"(LELE的粉丝,即

【Leetcode长征系列】Construct Binary Tree from Inorder and Postorder Traversal

原题: Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路:和上一题一样,后续我们可以通过最后一个值得到根的值,同样可以通过定位根的值得到左右子树的子集,递归求解即可. 代码: /** * Definition for binary tree * struct Tre

【Leetcode长征系列】Single Number II

原题: Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 思路: 用一个32位的数组存每一位bit值之后.得到答案后每一位除

【Leetcode长征系列】Pow(x, n)

原题: Implement pow(x, n). 思路:递归计算pow. class Solution { public: double pow(double x, int n) { long long int mid = n/2; int d = n%2; if(n==0) return 1; if(n==1) return x; if(d==1) return pow(x, (n/2)+1) * pow(x, n/2); else return pow(x, n/2) * pow(x, n/

【Leetcode长征系列】Sqrt(x)

原题: Implement int sqrt(int x). Compute and return the square root of x. ==============================以下为引用==================================== 牛顿迭代法 为了方便理解,就先以本题为例: 计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示. 首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交

【Leetcode长征系列】Balanced Binary Tree

原题: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1. 思路:递归判断左右子树是否为BST. 代码: /** * Def