美文网首页
算法练习

算法练习

作者: Chris_Cui | 来源:发表于2020-01-14 15:22 被阅读0次

将字符串转化为数字,实现int()方法

s = '298476'
n = 298476
s = s[::-1]
number = 0
for i, e in enumerate(s):
    print(i, e)
    for j in range(0, 10):
        if e == str(j):
            number += j*(10**i)
print(number)

回文数

def isPalindrome(x):
    if x < 0:#当数字是负数的时候必然不是回文数
        return False
    result = 0
    temp = x
    while temp != 0:
        result = result * 10 + temp % 10
        temp = temp // 10
        print(result, temp)
    return x == result

res = isPalindrome(1221)
print(res)

俩数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素

arr=[1,3,6,15]
target=9
# 一遍哈希表
def two_sum_with_dict2(nums, target):
    _dict = {}
    for i, e in enumerate(nums):
        if _dict.get(target - e) is not None:
            return (_dict.get(target - e), i)
        _dict[e] = i

res=two_sum_with_dict2(arr,target)
print(res)

# 暴力循环
def twoSum(nums,target):
    for i, m in enumerate(nums):
        j=i+1
        while j<len(nums):
            if target == m+nums[j]:
                return [i,j]
            else:
                j+=1

res = twoSum(arr,target)
print(res)

反转字符串

eStr=["h","e","l","l","o"]
outputStr=["o","l","l","e","h"]
eStr.reverse()
# 双向指针
i, j = 0, len(eStr)-1
while i<j:
    eStr[i], eStr[j]=eStr[j],eStr[i]
    i+=1
    j-=1

反转字符串里的单词

rStr = "the sky is blue"
# 方法一
newrStr = rStr.split()
i, j = 0, len(newrStr)-1
while i < j:
    newrStr[i], newrStr[j] = newrStr[j], newrStr[i]
    i+=1
    j-=1
print(' '.join(newrStr))
# 方法二
print(' '.join(rStr.split()[::-1]))

冒泡排序

def bubbo_sort(arr):
    length = len(arr)
    for i in range(length):
        for j in range(length-i-1):
            if arr[j] > arr[j+1]:
                # tmp = arr[j]
                # arr[j]=arr[j+1]
                # arr[j+1]=tmp
                arr[j], arr[j+1] = arr[j+1], arr[j]

arr=[1,3,4,5,6,8,2,7]
bubbo_sort(arr)
print(arr)

相关文章

  • 前端干货 -03

    37. 算法 算法地址 数据结构与算法 JavaScript 描述. 章节练习https://github.com...

  • 算法-心得

    本周大部分的时间都在练习算法。虽说是有点被逼迫的意思,但是算法还是很重要的,也需要自己练习。 说到算法,我自身的感...

  • 算法练习(-)

    You are a professional robber planning to rob houses alon...

  • 算法练习

    将字符串转化为数字,实现int()方法 回文数 俩数之和 给定一个整数数组 nums 和一个目标值 target,...

  • 算法练习

    背景 Find closing/opening parenthesis You will be implement...

  • 算法练习

    2021 三月份 1. 两数之和 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 ...

  • 刷算法 - 算法练习

    最近断断续续的刷了一些基础算法题. 我们做移动端开发的, 刷算法题有意义吗? 如果对这个问题有疑问, 可以在读这篇...

  • 2018-11-11 算法练习题

    下面是几道算法练习题:

  • iOS + 常用排序算法

    算练习吧参照的原文常用排序算法总结(一)八大排序算法

  • 笨办法学C 练习39:字符串算法

    练习39:字符串算法 原文:Exercise 39: String Algorithms 译者:飞龙 这个练习中,...

网友评论

      本文标题:算法练习

      本文链接:https://www.haomeiwen.com/subject/lzhaactx.html