code exercise 1-3

code 1
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

code:

nums=[2,7,5,8]target=12buff_dict={}for i in range(len(nums)):    print(i)    if nums[i] in buff_dict :        print([buff_dict[nums[i]],i])    else:        buff_dict[target-nums[i]]=i        print(buff_dict)

output:

0{10: 0}1{10: 0, 5: 1}2[1, 2]3{10: 0, 5: 1, 4: 3}

笔记:

将和的另一个值,依次作为字典的键值存入字典中,遍历数组,确定差值是否在字典中,如果不在作为键存入,键值对应的值和数组的索引相同。如果差值在字典中,则输对应的字典中键对应的值。

code 2 

找出字符串中第一个字符串中的字母的下标

s="leetcode"

return 0

s="loveleetcode"

return 2

code:

def firstUniqChar(self,s):

    letter='abcdefghijklmnopqrstuvwxyz'

    index=[s.index(l)  for  l in  letters  if  s.count(l)==1]

    return min(index) if len(index)>0 else -1

笔记:s.count()作用 方法用于统计字符串里某个字符出现的次数。s.index()一般用处是在序列中检索参数并返回第一次出现的索引,没找到就会报

code 3

给出一位整数,输出它顺序相反的数

例:输入123 输出321 

      数入-123 输出 -321

      输入 120 输出 21

code :解法1

          class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        n=abs(x)
        y=0
        while n!=0: 
                y=10*y+n%10
                n=n//10
        if x<0:
            y=-y
        if y<(-2**31) or y>(2**31-1):
            return 0
        else:

            return y

笔记:1对于整数,不需要像字符串,数组那样用len来确定长度,n!=0 就是一个不错判断。

         2 “/”和“//”区别,前面是浮点数除法。后面是整数除法,**平方

 解法 2:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        s = list(str(x))
        if x>=0:
            res = s[::-1]
            num = int(''.join(res))
        else:
            res = s[1:][::-1]
            num = int(''.join(res))*(-1)
        if num>(2**31)-1 or num<-(2**31): return 0

        else:return num

笔记:1 把数字转化为字符串  2 b = a[i:j:s]这种格式呢,i,j与上面的一样,但s表示步进,缺省为1,i,表示a的起始索引,j表示要索引的结尾,s表示步长。s=-1时表示倒序

s='hello world\n' 
print s[:-1]
打印 hello world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值