备战程序设计大赛-LintCode刷题记录(三)

本文介绍了两种常见的搜索算法:字符串查找和二分查找。通过具体实例,文章详细讲解了如何使用C++实现这两种算法,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

13. 字符串查找

题目来源:LintCode



题目:
对于一个给定的 source 字符串和一个 target字符串, 你应该在 source 字符串中找出 target 字符串
出现的第一个位置(从0开始), 如果不存在, 则返回 -1.


样例
如果 source = "source" 和 target = "target", 返回 -1
如果 source = "abcdabcdefg" 和 target = "bcd", 返回 1

难度级别:
容易

使用的编程语言:
C++

思路分析:
看到题目马上提炼出问题的核心:找子串的索引. 马上想到 String类自带函数里的find()方法刚好能做到这一点,
假如没找到子串, 就会返回-1, 与题意吻合.所以直接将传入的字符数组转成字符串, 直接进行操作, 非常简便
实现代码:
class Solution {
public:
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    int strStr(const char *source, const char *target) {
        int index = 0;
        if (source == NULL || target == NULL)
        {
            index = -1;
            return index;
        }
        string t = (target);
        string s = (source);
        /*char* temp = new char[100];
        strncpy(temp, target, target.length());*/
        index = s.find(t);
        return index;
    }
};

14. 二分查找

题目来源:LintCode



题目:
给定一个排序的整数数组(升序) 和一个要查找的整数 target, 用O(logn)的时间查找到target第一次出现的下标(从0开始),
如果 target不存在于数组中, 返回 -1.


样例
在数组 [1, 2, 3, 3, 4, 5, 10]中二分查找3, 返回2.

难度级别:
中等

使用的编程语言:
C++

思路分析:
我花在这道题上的时间比上一道多了十几倍, 虽然利用二分查找法找索引是没有什么难度,
但就在找最小索引处卡住, 随后我用了一种"奇葩"方法, 希望以后随着题量增多能有所改观.
实现代码:
int binarySearch(vector<int> &array, int target) 
    {
        int counter = 0, temp = 0, mid = 0;
        int low = 0, high = array.size();
        while (low <= high)
        {
            mid = (low+high)/2;
    		if (array[mid] == target) 
    		{
    			counter++;
                        //寻找最小索引
    			for (int i = mid; i >= low; i--)
    			{
    				if (array[i] == target)
    				{
    					temp = i;	
    				}
    			}
    			return temp;
    		}
    		else if (array[mid] > target)
    		{
    			high = mid-1;
    		}
    		else
    		{
    			low = mid+1;
    		}
        }
        return -1;
    }
};






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值