leetcode 1、2、3、122小结
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
1、Brute Force:双层循环;
2、哈希定位优化。
2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
1、初始投机取巧想将两个链表转化为数字,从第一个元素开始遍历
r1 += (p->val*t);
t *= 10;
然后相加得到第三个数字,再转换为链表,但后期测试数据超过int的最大范围,尝试改成double,但小数位数导致了很多错误,且后期数字转链表需取余,而取余只对int型进行计算,最终还是采取最简单的逐个相加的方法
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
1、最简单的就是三层循环Brute Force,觉得时间复杂度过大,于是采用空间换时间,用大小为128的数组存储每一个字符的频率,双蹭循环,但提交依然卡在一个很长的测试字符串上,超时,事实上用leetcode示例的Brute Force的代码提交,依然超时
2、然后考虑用两个指针进行优化,源码(好短…):
int lengthOfLongestSubstring(char* s) {
int letter[128]={0}, i=0, j=0, num=0, max=0;
while( i<strlen(s)&&j<strlen(s) ){
if(letter[s[j]] == 0)
{
letter[s[j]]++;
// printf("%d %d %d %d %d %d\n",i,j,s[i],s[j],letter[s[i]],letter[s[j]]);
j++;
num=j-i;
}
else{
letter[s[i]]--;
// printf("%d %d %d %d %d %d\n",i,j,s[i],s[j],letter[s[i]],letter[s[j]]);
i++;
}
if( max<num ){
max = num;
}
}
printf("%d", max);
return max;
}
后期发现这个其实就是LeetCode示例的Sliding Window的方法;
3、模式匹配kmp中next数组存储与当前字符有相同前缀的字符位置,考虑也可用在算法中。
122. Best Time to Buy and Sell Stock II
题目:Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
1、双层循环。
2、数组递增,便可一直向后遍历,计算price[i]和price[i-1]的差,进行累加,若是非递增,停止累加。源码:
int maxProfit(int* prices, int pricesSize) {
int i;
int sum = 0;
for( i = 0; i < pricesSize-1; i++ )
{
if(prices[i]<prices[i+1])
{
sum+=(prices[i+1]-prices[i]);
}
}
printf("%d",sum);
return sum;
}
时间复杂度达到0(n),写完才发现大多代码还是双层循环,感觉比示例优化代码要优化一丢丢…