python_lintcode_397最长上升连续子序列_56两数之和
2017-09-16 16:27
260 查看
397最长上升连续子序列
题目
给定一个整数数组(下标从 0 到 n-1, n 表示整个数组的规模),请找出该数组中的最长上升连续子序列。(最长上升连续子序列可以定义为从右到左或从左到右的序列。)注意事项
time
样例
给定 [5, 4, 2, 1, 3], 其最长上升连续子序列(LICS)为 [5, 4, 2, 1], 返回 4.
给定 [5, 1, 2, 3, 4], 其最长上升连续子序列(LICS)为 [1, 2, 3, 4], 返回 4.
思路
if a<=2:return a先判断数组的第一个元素和第二个元素之间的关系是越来越大还是越来越小(此处定义为0 or 1),此处连续子序列已经至少有两个,即sum=2
对后面的数组元素进行判断,满足一开始的关系(0 or 1),sum+1,直到关系发生改变(0->1 or 1->0),比较存放最大次数的comp和sum,将最大值放于sum.
循环3,直到读取到最后一个元素
return comp
代码
class Solution: """ @param: A: An array of Integer @return: an integer """ def longestIncreasingContinuousSubsequence(self, A): # write your code here a=len(A) if a<=2:return a #b=0 越来越大,b=1 越来越小 b=0 if A[0]>A[1]:b=1 #sum存放每次出现连续的次数,comp存放最大的连续次数 sum=2 comp=0 for i in range(2,a): #连续情况 if A[i]>A[i-1] and b==0 or A[i]<A[i-1] and b==1: sum+=1 #出现没有连续,所有初始化,并判断是否改变comp if A[i]>A[i 4000 -1] and b==1 or A[i]<A[i-1] and b==0: if comp<sum:comp=sum sum=2 #b=0 越来越大,b=1 越来越小 b=0 if A[i-1]>A[i]:b=1 #可能出现最长上升连续子序列连续到最后一个元素,需要将此次与之前的最大的连续次数判断 if comp<sum:comp=sum return comp
56两数之和
题目
给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。
注意事项
你可以假设只有一组答案。
样例
给出 numbers = [2, 7, 11, 15], target = 9, 返回 [1, 2].
思路
此列表都是按升序排好的本结果可多个,只需返回一组即可
选取列表liat1的第一个元素A,然后再去建立新的除了该元素之外的列表list2,判断target-A是否在新的列表,没有则取list2x下一个元素B
循环1,直到找到满足要求的两个数字
找到之后,所以第一个数字在list1为i,第二个数字是在list2的位置j,转化在list1的位置,应该j+i+1,即[i,j+i+1]
因为列表都是从0开始的,而题目要求的下标的范围是 1 到 n,不是以 0 开头,结果应该为[i+1,i+j+2]
目标数字为6: 可以为1+5 list1:123456789 位置 :012345678 第一个 i=0 将1除去,得到新的列表list2 list2:23456789 位置 :01234567 第二个 j=3 在list1的位置 4=j+i+1 即 [0,4] 结果 [1,5]
代码
class Solution: """ @param numbers : An array of Integer @param target : target = numbers[index1] + numbers[index2] @return : [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, numbers, target): # write your code here if len(numbers)<2:return [] a=len(numbers) #从第一个数字到a-1,因为第a个不需要找,没有第二个数给他相加 for i in range(a-1): j=target-numbers[i] if j in numbers[i+1:]: #返回满足条件的下标,此下标是在新的列表的下标,需要+前面数 i2=numbers[i+1:].index(j)+i+2 return [i+1,i2] return []
相关文章推荐
- lintcode 最长上升连续子序列 II(二维最长上升连续序列)
- [LintCode 124] 最长连续序列(Python)
- lintcode-397-最长上升连续子序列
- 最长上升连续子序列-LintCode
- lintcode-最长上升连续子序列-397
- Lintcode 114.最大上升连续子序列
- [Lintcode 397] 最长上升连续子序列(Python)
- LintCode刷题——最长上升连续子序列
- LintCode- 最长上升连续子序列
- lintcode ----最长连续序列
- 最长非上升/非下降子序列(O(nlogn)非连续)
- 最长上升连续子序列(LintCode)
- 最长连续序列-LintCode
- lintcode:最长上升连续子序列
- python剑指offer系列和为S的连续正数序列
- LintCode 最长上升连续子序列
- 最长上升连续子序列
- [LintCode] Longest Consecutive Sequence 求最长连续序列
- Python :连续正数序列
- 最长上升连续子序列