LeetCode 剑指Offer 练习

目录

题目整理来源:[https://zhuanlan.zhihu.com/p/112990684](LeetCode By Python: 剑指Offer第2版 解题目录)

数据结构

LCR 120. 寻找文件副本

[https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/solutions/](LCR 120. 寻找文件副本)

1.第一次想的是遍历对比
2.使用Hash

使用 Dictionary

public class Solution {
    public int FindRepeatDocument(int[] documents) {
Dictionary<int, int> valMap = new Dictionary<int, int>();

for (int i = 0; i < documents.Length; i++) {
	if (valMap.TryGetValue(documents[i], out int j))
		return documents[i];
	valMap.Add(documents[i], i);
}
return -1;
    }
}

LCR 121. 寻找目标值 - 二维数组

[https://leetcode.cn/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/description/](LCR 121. 寻找目标值 - 二维数组)

遍历每一行,然后用二分查找

public class Solution {
    public bool FindTargetIn2DPlants(int[][] plants, int target) {
 foreach (var row in plants)
 {
		if (DichotomySort(row, target) != -1)
return true;
	}
 return false;
    }


/// 二分查找
int DichotomySort(int[] nums,int target) {

	int left=0, right = nums.Length-1;

	while (left<=right) {

		int middle = left + ((right - left) >> 1);
		if(target== nums[middle])
			return middle;
		if (target>nums[middle]) {
		   left = middle + 1;
		}
		else {
		   right = middle - 1;
		}

	}
	return -1;
}
}

替换空格

https://leetcode.cn/problems/ti-huan-kong-ge-lcof/description/

过于简单,不贴代码了
1.Replace
2.双指针,从数组前后扫,是点就换成空字符

posted @ 2024-03-21 20:35    阅读(35)  评论(0)    收藏  举报