算法题集锦go、java

1.两数之和

func twoSum(nums []int, target int) []int {
    hashTable := map[int]int{}
    for i,x := range(nums){
        if p,ok := hashTable[target-x];ok{
            return []int{p,i}
        }
        hashTable[x]=i
    }
    return nil
}
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> hashtable = new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(hashtable.containsKey(target-nums[i])){
                return new int[]{hashtable.get(target-nums[i]),i};
            }
            hashtable.put(nums[i],i);
        }
        return new int[0];
    }
}

回文数

func isPalindrome(x int) bool {
    if x<0 || (x %10 ==0 && x!=0){
        return false
    }

    revertedNumber := 0
    for x > revertedNumber {
        revertedNumber = revertedNumber * 10 + x%10
        x /= 10
    }
    return x == revertedNumber || x==revertedNumber/10
}
class Solution {
    public boolean isPalindrome(int x) {
        if (x <0 || (x %10 == 0 && x !=0)){
            return false;
        }
        int revertedNumber = 0;
        while (x>revertedNumber){
            revertedNumber = revertedNumber *10 + x%10;
            x /=10;
        }
        return x == revertedNumber || x==revertedNumber/10;
    }
}

罗马数字转整数串

func romanToInt(s string) int {
    var symbolValues = map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    n := len(s)
    var ans = 0
    for i := range(s){
        value := symbolValues[s[i]]
        if i < n-1 && value < symbolValues[s[i+1]]{
            ans -= value
        }else{
            ans+=value
        }
    }
    return ans

}
class Solution {
    Map<Character, Integer> symbolValues = new HashMap<>(){{
            put('I',1);
            put('V',5);
            put('X', 10);
            put('L', 50);
            put('C', 100);
            put('D', 500);
            put('M', 1000);
        }};
    public int romanToInt(String s) {
        int ans = 0;
        int n =s.length();
        for (int i = 0;i<n;i++){
            int value = symbolValues.get(s.charAt(i));
            if (i <n-1 && value < symbolValues.get(s.charAt(i+1))){
                ans -= value;
            }else{
                ans +=value;
            }
        }
        return ans;
    }
}

最长公共前缀

func longestCommonPrefix(strs []string) string {
    if len(strs) == 0{
        return ""
    }
    firststr := strs[0]
    n := len(firststr)
    for i:=0;i<n;i++ {
        for j:=1;j<len(strs);j++{
            if (len(strs[j]) <= i || strs[j][i] !=firststr[i]){
                return firststr[:i]
            }
        }
    }
    return firststr
}

有效的括号

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0){
            return "";
        }
        String prefix = strs[0];
        int n = prefix.length();
        for(int i=0;i<n;i++){
            for (int j=1;j<strs.length;j++){
                if (strs[j].length() <= i || strs[j].charAt(i) != prefix.charAt(i)){
                    return prefix.substring(0,i);
                }
            }
        }
        return prefix;
    }
}
func isValid(s string) bool {
    var n int = len(s)
    if (n%2==1){
        return false
    }
    pairs := map[byte]byte{')':'(',']':'[','}':'{'}
    stack := []byte{}
    for _,c := range []byte(s){
        if _ ,ok := pairs[c];ok{
            if len(stack)==0 || stack[len(stack)-1] != pairs[c]{
                return false
            }
            stack=stack[:len(stack)-1]
        }else{
            stack = append(stack,c)
        }
    }
    return len(stack) == 0
}

合并两个有序列表

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
    dummy := &ListNode {}
    cur := dummy
    for list1 != nil && list2 != nil{
        if list1.Val < list2.Val{
            cur.Next = list1
            list1=list1.Next
        }else{
            cur.Next = list2
            list2=list2.Next
        }
        cur = cur.Next
    }
    if list1 != nil{
        cur.Next=list1
    }else{
        cur.Next = list2
    }
    return dummy.Next

}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val<list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else{
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if (list1 != null){
            cur.next = list1;
        }else{
            cur.next = list2;
        }
        return dummy.next;
    }
}
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
    if list1 == nil {
        return list2
    }
    if list2 == nil {
        return list1
    }
    if list1.Val <list2.Val{
        list1.Next=mergeTwoLists(list1.Next,list2)
        return list1
    }
    list2.Next = mergeTwoLists(list1,list2.Next)
    return list2

}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null){
            return list1;
        }
        if (list1.val < list2.val){
            list1.next = mergeTwoLists(list1.next,list2);
            return list1;
        }else{
            list2.next = mergeTwoLists(list1,list2.next);
            return list2;
        }

    }
}

删除有序数组中的重复项

func removeDuplicates(nums []int) int {
    var i,j int
        j=0
        for i=1;i<len(nums);i++ {
            if nums[i]!=nums[j]{
                j+=1
                nums[j]=nums[i]
            }
        }
        return j+1
}
class Solution {
    public int removeDuplicates(int[] nums) {
        int j = 0;
        for (int i=0;i< nums.length;i++){
            if (nums[i] != nums[j]){
                j+=1;
                nums[j]=nums[i];
            }
        }
        return j+1;
    }
}

移除元素

class Solution {
    public static int removeElement(int[] nums, int val) {
        int j = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] !=val){
                nums[j]=nums[i];
                j+=1;
            }
        }
        return j;
    }
}
func removeElement(nums []int, val int) int {
    j := 0
    for i := 0;i<len(nums);i++{
        if nums[i]!=val{
            nums[j]=nums[i]
            j+=1
        }
    }
    return j
}

找出字符串中第一个匹配项的下标

func strStr(haystack string, needle string) int {
    return strings.Index(haystack, needle)
}
func strStr(haystack string, needle string) int {
    n := len(needle)
    for i:=0;i<len(haystack)-n+1;i++{
        if haystack[i]==needle[0] && same(haystack[i:i+n], needle){
            return i
        }
    }
    return -1
}

func same(str1 string, str2 string) bool {
    if len(str1) != len(str2){
        return false
    }
    for i := 0;i<len(str1);i++ {
        if str1[i] != str2[i]{
            return false
        }
    }
    return true
}
class Solution {
    public int strStr(String haystack, String needle) {
        // 检查needle是否为空字符串
        if (needle.isEmpty()) {
            return 0;
        }
        // 使用indexOf方法查找子字符串
        return haystack.indexOf(needle);
    }
}

搜索插入位置

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}
func searchInsert(nums []int, target int) int {
    var i,j int = 0,len(nums)-1
    var mid int
    for ;i<=j;{
         mid = (i+j) / 2 
        if nums[mid]==target{
            return mid
        }else if nums[mid]<target{
            i = mid +1
        }else{
            j=mid-1
        }
    }
    return i

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值