[心得]面试题分析与整理4

13.求单链表环路的起点
此为面试金典126题
思路是一快一慢,相遇后同步移动至相等。


NodeLink getRingStart(NodeLink head)
{
    if(!head)   return 0;
    NodeLink fast, slow;
    fast = slow = head;
    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast)    break;
    }

    if(!fast)   return slow;
    else if(!fast->next)    return fast;

    slow = head;
    while(slow != fast)
    {
        slow = slow->next;
        fast = fast->next;
    }
    return fast;
}

14.给定N个数,找出超过一半的一个数。此为编程之美129页原题。

int findMorethanHalf(int *a, int n)
{
    if(n<0) return 0;
    int res = a[0];
    int times = 0;
    for(int i=0;i<n;++i)
    {
        if(!times)
        {
            res = a[i];
            ++times;
        }
        else
        {
            if(a[i]==res)   ++times;
            else
                --times;
        }
    }
    return res;
}

扩展问题,如果有出现超过1/4
则需要至少保存3个数字

15.最长连续子序列之和
如果是环形
拆解成2n的数组来求解
编程金典318页,编程之美183页

#include <iostream>
using namespace std;

void longestSubSeq(int *a, int n);

int main()
{
    int a[]={1,-1,2,-3,4,-5,6,-7};
    longestSubSeq(a, 8);
    return 0;
}

void longestSubSeq(int *a, int n)
{
    int thisSum, maxSum;
    thisSum = maxSum = 0;
    for(int i=0;i<n;++i)
    {
        thisSum+=a[i];
        if(thisSum>maxSum)
            maxSum = thisSum;
        else if(thisSum<0)
            thisSum=0;
    }
    cout<<maxSum<<endl;
}

16.字符串按字母顺序排序,要求不用库函数。

#include <iostream>
#include <cstring>
using namespace std;

void sortString(char *str, int n);

int main()
{
    char str[]="terminalm";
    sortString(str, 10);
    return 0;
}

void sortString(char *str, int n)
{
    int cnt[26];
    for(int i=0;i<26;i++)
        cnt[i]=0;

    for(int i=0;i<n;i++)
        if(str[i]>='a' && str[i]<='z')
            ++cnt[str[i]-'a'];

    for(int i=0;i<26;i++)
        if(cnt[i])
            for(int j=cnt[i];j>0;--j)
                cout<<(char)('a'+i);
    cout<<endl;
}

目前的解法没有考虑大小写问题
后续可以改进

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值