LeetCode--1、26、27、35、53 Array(Easy)


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.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目地址:https://leetcode.com/problems/two-sum/description/

题意:给定一个整形数组和一个目标,返回数组中相加等于目标的两个数的下标

思路:创建一个hash表,枚举每一个数n,把数值作为key,下标作为values,遍历时找target-n

python

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d ={}
        for i, n in enumerate(nums):
            m = target - n
            if m in d:
                return[d[m],i]
            else:
                d[n] = i


26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example:

Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn‘t matter what you leave beyond the new length.
题目地址:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
题意:给定一个已经排序好的数组,用O(1)的空间在原数组去掉重复的数,返回新的长度
思路:利用双指针,一个指向当前不重复的长度len,一个指向遍历看不重复的写到len
python
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums == []:
            return 0
        index = 0
        for i in range(1,len(nums)):
            if nums[index] != nums[i]:
                index += 1
                nums[index] = nums[i]
        return index+1

27. Remove Element

Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.

Example:

Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
题目地址:https://leetcode.com/problems/remove-element/description/
题意:给定一个数组和目标,在原位将数组中的目标值删除,返回新的长度
思路:双指针
python
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        j = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[j] = nums[i]
                j += 1
        return j

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 1:

Input: [1,3,5,6], 0
Output: 0
题目地址:https://leetcode.com/problems/search-insert-position/description/
题意:给定一个数组和target,如果在数组里找到target,返回target的下标,如果找不到返回插入的位置
思路:二分法
python
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        start, end = 0, len(nums)
        while start < end:
            mid = (start+end) / 2
            if nums[mid] < target:
                start =  mid+1
            else:
                end = mid
        return start

53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

题目地址:https://leetcode.com/problems/maximum-subarray/description/

题意:找出连续子数组的最大和

思路:动态规划问题

python
class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans, sum = nums[0], 0
        for x in nums:
            sum += x
            if sum > ans:
                ans = sum
            if sum < 0:
                sum = 0
        return ans

原文地址:https://www.cnblogs.com/huangqiancun/p/8387592.html

时间: 2024-08-29 15:56:36

LeetCode--1、26、27、35、53 Array(Easy)的相关文章

由数字、26个英文字母、下划线或汉字的正则表达式

1.由数字.26个英文字母或者下划线组成的字符串: ^[0-9a-zA-Z_]{1,}$ 2.非负整数(正整数 + 0 ): ^/d+$ 3. 正整数: ^[0-9]*[1-9][0-9]*$ 4.非正整数(负整数 + 0): ^((-/d+)|(0+))$ 5. 负整数 : ^-[0-9]*[1-9][0-9]*$ 6.整数: ^-?/d+$ 7.非负浮点数(正浮点数 + 0): ^/d+(/./d+)?$ 8.正浮点数 : ^(([0-9]+/.[0-9]*[1-9][0-9]*)|([0-

连载:面向对象葵花宝典:思想、技巧与实践(35) - NOP原则

NOP,No Overdesign Priciple,不要过度设计原则. 这应该是你第一次看到这个原则,而且你也不用上网查了,因为这个不是大师们创造的,而是我创造的:) 之所以提出这个原则,是我自己吃过苦头,也在工作中见很多人吃过类似的苦头. 你可能也见过这样的场景: 产品提出了一个需求,设计师眼光非常长远,他甚至把5年后可能的业务变化都提出来并且加以设计了,让你不得不佩服设计师的高瞻远瞩的眼光,并且由衷的从心底赞叹:牛逼啊! 但很快你就会发现,设计师是很牛逼,但你开发的时候就很苦逼了,设计方案

Leetcode:Construct Binary Tree 前序和中序、后序和中序构建二叉树

前序和中序构建二叉树 后序和中序构建二叉树 分析:主要思路就是 在中序中找根节点然后划分左右子树,具体如下: 1. 查找根节点. 我们知道前序序列的第一个元素 和 后序序列的最后一个元素 肯定是根节点,我们就以此为突破口 2. 确定根节点的坐标. 我们在 中序序列中找到 根节点 的下标. 3. 分割左右子树. 对于中序序列:根节点下标之前的都属于左子树,之后的都属于右子树 对于先序序列:根节点之后的 一段元素(该段长度可以由中序序列的左子树长度确定)属于左子树,左子树之后的元素属于右子树 对于先

【足迹C++primer】35、特定容器算法

特定容器算法 lst.merge(lst2) 将来自lst2的元素并入到lst.这两个都必须是有序的. lst.merge(lst2, comp) 元素将从lst2删除,第一个版本使用<运算符,第二个版本使用给定的运算符 lst.remove(lst2)调用erase删除掉与给定值相等(==)或令一元谓词为真的每个元素 lst.remove_if(pred) lst.reverse() 反转lst中元素的顺序 lst.sort() 使用<或给定比较操作排序元素 lst.sort(comp) l

35、concurrent.futures模块与协程

concurrent.futures  -Launching parallel tasks    concurrent.futures模块同时提供了进程池和线程池,它是将来的使用趋势,同样我们之前学习的进程池Pool和threadpool模块也可以使用. 对进程池疑惑的可以参阅:32进程池与回调函数http://www.cnblogs.com/liluning/p/7445457.html 对threadpool模块疑惑的可以看我闲暇时写的一段代码:(因为本人也不了解这个模块,代码里写的也是自己

程序猿之---C语言细节27(函数无参数时细节、函数默认返回int型证明、return默认还回值、void指针++操作)

主要内容:函数无参数时细节.函数默认返回int型证明.return默认还回值.void指针++操作 一.函数无参数时细节 函数无参数时应该加上void 在c语言中一个函数 void f(); 在使用时传递参数f(2);没有报错,而在c++中则会报错 最好加上void来明确函数是无参数的 二.函数默认返回类型为int型 见下面程序 三.return默认返回1 细节:return不可返回执行栈内存中的指针,因为该内存在函数体结束时自动销毁 四.void 指针++操作 void *p; p++; //

block使用小结、在arc中使用block、如何防止循环引用

引言 使用block已经有一段时间了,感觉自己了解的还行,但是几天前看到CocoaChina上一个关于block的小测试主题 : [小测试]你真的知道blocks在Objective-C中是怎么工作的吗?,发现竟然做错了几道, 才知道自己想当然的理解是错误的,所以抽时间学习了下,并且通过一些测试代码进行测试,产生这篇博客. Block简介(copy一段) Block作为C语言的扩展,并不是高新技术,和其他语言的闭包或lambda表达式是一回事.需要注意的是由于Objective-C在iOS中不支

Objective-C-类(static)方法、实例方法、overwrite(覆写)、属性(property)复习

先来定义一个Human父类 定义部分: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // //  Human.h //  OOP // //  Created by jimmy.yang on 11-2-9. //  Copyright 2011 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface Human :

33、任务三十三——棋盘的实现、正方体的移动效果

0.题目 如图,实现一个类似棋盘的格子空间,每个格子用两个数字可以定位,一个红正方形的DOM在这个空间内,正方形中的蓝色边表示这是他的正面,有一个input输入框 在输入框中允许输入如下指令,按下按钮后,使得正方形做相应动作 GO:向蓝色边所面向的方向前进一格(一格等同于正方形的边长) TUN LEF:向左转(逆时针旋转90度) TUN RIG:向右转(顺时针旋转90度) TUN BAC:向右转(旋转180度) 移动不能超出格子空间 1.解题过程 1 <!DOCTYPE html> 2 <