34. Search for a Range

本文介绍了一种在有序整数数组中查找指定目标值起始和结束位置的方法,算法的时间复杂度为O(logn)。通过两次二分查找实现,首次确定目标值的起始位置,再次确定目标值的结束位置。

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路:时间复杂度为O(log n),首先想到二分法,其次再确定二分判断关系和坐标转移关系。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res(2, -1);
        if(nums.empty()) return res;

        int n = nums.size();
        int left = 0, right = n - 1;
        while(left < right) {
            int mid = (left+right) / 2;
            if(target > nums[mid]) {                // 二分关系确保left为最左边坐标
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        if(nums[left] != target) return res;
        res[0] = left;
        right = n-1;
        while(left < right) {
            int mid = (left+right) / 2 + 1;      // 加1确保不会出现死循环
            if(target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid;
            }
        }
        res[1] = right;

        return res;
    }
};
### Hierarchical Embedding Model for Personalized Product Search In machine learning, hierarchical embedding models aim to capture the intricate relationships between products and user preferences by organizing items within a structured hierarchy. This approach facilitates more accurate recommendations and search results tailored specifically towards individual users' needs. A hierarchical embedding model typically involves constructing embeddings that represent both product features and their positions within a category tree or other organizational structures[^1]. For personalized product searches, this means not only capturing direct attributes of each item but also understanding how these relate across different levels of abstraction—from specific brands up through broader categories like electronics or clothing. To train such models effectively: - **Data Preparation**: Collect data on user interactions with various products along with metadata describing those goods (e.g., price range, brand name). Additionally, gather information about any existing hierarchies used in categorizing merchandise. - **Model Architecture Design**: Choose an appropriate neural network architecture capable of processing multi-level inputs while maintaining computational efficiency during training sessions. Techniques from contrastive learning can be particularly useful here as they allow systems to learn meaningful representations even when labels are scarce or noisy[^3]. - **Objective Function Formulation**: Define loss functions aimed at optimizing performance metrics relevant for ranking tasks; minimizing negative log-likelihood serves well as it encourages correct predictions over incorrect ones[^4]. Here’s a simplified example using Python code snippet demonstrating part of what might go into building one aspect of this kind of system—learning embeddings based off some hypothetical dataset containing customer reviews alongside associated product IDs: ```python import torch from torch import nn class HierarchicalEmbedder(nn.Module): def __init__(self, vocab_size, embed_dim=100): super().__init__() self.embedding = nn.Embedding(vocab_size, embed_dim) def forward(self, x): return self.embedding(x) # Example usage: vocab_size = 5000 # Number of unique words/products embeddings_model = HierarchicalEmbedder(vocab_size) input_tensor = torch.LongTensor([i for i in range(10)]) # Simulated input indices output_embeddings = embeddings_model(input_tensor) print(output_embeddings.shape) # Should output something similar to "torch.Size([10, 100])" ``` This script initializes a simple PyTorch module designed to generate fixed-size vector outputs corresponding to given integer keys representing either textual tokens found within review texts or numeric identifiers assigned uniquely per catalog entry.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值